forked from haskell/hackage-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImportClient.hs
1023 lines (842 loc) · 34.8 KB
/
ImportClient.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE PatternGuards, ScopedTypeVariables, OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module Main where
import Network.HTTP
import Network.Browser hiding (err)
import Network.URI
( URI(..), URIAuth(..), parseURI, escapeURIString, isUnescapedInURI )
import qualified Distribution.Client.HtPasswdDb as HtPasswdDb
import qualified Distribution.Client.UserAddressesDb as UserAddressesDb
import qualified Distribution.Client.UploadLog as UploadLog
import qualified Distribution.Client.TagsFile as TagsFile
import qualified Distribution.Client.DistroMap as DistroMap
import qualified Distribution.Client.PkgIndex as PkgIndex
import Distribution.Server.Users.Types (UserName(..))
import Distribution.Server.Util.Parse (packUTF8, unpackUTF8)
import Distribution.Package
( PackageId, PackageName, packageName, packageVersion )
import Distribution.Version
( Version, versionTags )
import Distribution.Text
( display, simpleParse )
import Distribution.Simple.Utils
( topHandler, die, {-warn, debug,-} wrapText )
import Distribution.Verbosity
( Verbosity, normal )
import Distribution.Simple.Command
import Distribution.Simple.Setup
( Flag(..), fromFlag, flagToList )
import Distribution.Client.ParseApacheLogs
import qualified Distribution.Server.Util.GZip as GZip
import System.Environment
( getArgs, getProgName )
import System.Locale
( defaultTimeLocale )
import System.Exit
( exitWith, ExitCode(..) )
import System.IO
import System.FilePath
( (</>), (<.>), takeFileName, dropExtension, takeExtension )
import qualified System.FilePath.Posix as Posix
import Data.List
import Data.Maybe
import Data.Ord (comparing)
import Data.Time (UTCTime, formatTime, getCurrentTime)
import Control.Monad
import Control.Monad.Trans
import Control.Applicative ((<$>))
import Data.ByteString.Lazy (ByteString)
import Data.Aeson (Value(..), toJSON, encode)
import Data.Text (Text)
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Text as Text
import qualified Data.Vector as Vector
import qualified Data.ByteString.Lazy as LBS
import qualified Text.CSV as CSV
import Control.Exception
import Control.Concurrent.Chan
import Control.Concurrent.Async
import qualified Paths_hackage_server as Paths (version)
--
-- The following data can be imported:
--
-- * User accounts
-- - user names
-- - htpasswd-style passwords
-- - email addresses
--
-- * Package metadata
-- - cabal files
-- - upload user
-- - upload times
-- - maintainer group
--
-- * Package tarballs
--
-- * Package deprecations
--
-- * Distribution information
--
-- * Documentation tarballs
--
-------------------------------------------------------------------------------
-- Top level command handling
--
main :: IO ()
main = topHandler $ do
hSetBuffering stdout LineBuffering
args <- getArgs
case commandsRun globalCommand commands args of
CommandHelp help -> printHelp help
CommandList opts -> printOptionsList opts
CommandErrors errs -> printErrors errs
CommandReadyToGo (globalflags, commandParse) ->
case commandParse of
_ | fromFlag (globalVersion globalflags) -> printVersion
CommandHelp help -> printHelp help
CommandList opts -> printOptionsList opts
CommandErrors errs -> printErrors errs
CommandReadyToGo action -> action globalflags
where
printHelp help = getProgName >>= putStr . help
printOptionsList = putStr . unlines
printErrors errs = do
putStr (concat (intersperse "\n" errs))
exitWith (ExitFailure 1)
printVersion = putStrLn $ "hackage-import " ++ display Paths.version
commands =
[ usersCommand `commandAddAction` usersAction
, metadataCommand `commandAddAction` metadataAction
, tarballCommand `commandAddAction` tarballAction
, distroCommand `commandAddAction` distroAction
, deprecationCommand `commandAddAction` deprecationAction
, docsCommand `commandAddAction` docsAction
, downloadCountCommand `commandAddAction` downloadCountAction
]
-------------------------------------------------------------------------------
-- Global command
--
data GlobalFlags = GlobalFlags {
globalVersion :: Flag Bool
}
defaultGlobalFlags :: GlobalFlags
defaultGlobalFlags = GlobalFlags {
globalVersion = Flag False
}
globalCommand :: CommandUI GlobalFlags
globalCommand = CommandUI {
commandName = "",
commandSynopsis = "",
commandUsage = \_ ->
"Data import client for the hackage server:\n"
++ "utility for importing old data into a new hackage-server\n",
commandDescription = Just $ \pname ->
"For more information about a command use\n"
++ " " ++ pname ++ " COMMAND --help\n\n"
++ "Main steps for populating a new empty server instance:\n"
++ concat [ " " ++ x ++ "\n"
| x <- ["users", "metadata", "tarballs"]],
commandDefaultFlags = defaultGlobalFlags,
commandOptions = \_ ->
[option ['V'] ["version"]
"Print version information"
globalVersion (\v flags -> flags { globalVersion = v })
(noArg (Flag True))
]
}
-------------------------------------------------------------------------------
-- Users command
--
data UsersFlags = UsersFlags {
usersHtPasswd :: Flag FilePath,
usersUploaders :: Flag Bool,
usersAddresses :: Flag FilePath,
usersJobs :: Flag String
}
defaultUsersFlags :: UsersFlags
defaultUsersFlags = UsersFlags {
usersHtPasswd = NoFlag,
usersUploaders = Flag False,
usersAddresses = NoFlag,
usersJobs = NoFlag
}
usersCommand :: CommandUI UsersFlags
usersCommand =
(makeCommand name shortDesc longDesc defaultUsersFlags options) {
commandUsage = \pname ->
"Usage: " ++ pname ++ " " ++ name ++ " [FLAGS] [URI]\n\n"
++ "Flags for " ++ name ++ ":"
}
where
name = "users"
shortDesc = "Import user accounts and other user data"
longDesc = Just $ \_ ->
"User account names and passwords can be imported from a "
++ "file in the\napache 'htpasswd' format.\n"
options _ =
[ option [] ["htpasswd"]
"Import an apache 'htpasswd' user account database file"
usersHtPasswd (\v flags -> flags { usersHtPasswd = v })
(reqArgFlag "HTPASSWD")
, option [] ["all-uploaders"]
"Add all new accounts to the uploaders group (use with --htpasswd)"
usersUploaders (\v flags -> flags { usersUploaders = v })
(noArg (Flag True))
, option [] ["addresses"]
"Import user email addresses"
usersAddresses (\v flags -> flags { usersAddresses = v })
(reqArgFlag "ADDRESSES")
, option [] ["jobs"]
"The level of concurrency to use when uploading"
usersJobs (\v flags -> flags { usersJobs = v })
(reqArgFlag "N")
]
usersAction :: UsersFlags -> [String] -> GlobalFlags -> IO ()
usersAction flags args _ = do
jobs <- validateOptsJobs (usersJobs flags)
baseURI <- validateOptsServerURI args
when (usersHtPasswd flags == NoFlag
&& usersAddresses flags == NoFlag) $
die $ "specify what to import using one or more of the flags:\n"
++ " --htpasswd= --addresses="
let makeUploader = fromFlag (usersUploaders flags)
case usersHtPasswd flags of
NoFlag -> return ()
Flag file -> importAccounts jobs file makeUploader baseURI
case usersAddresses flags of
NoFlag -> return ()
Flag file -> importAddresses jobs file baseURI
importAccounts :: Int -> FilePath -> Bool -> URI -> IO ()
importAccounts jobs htpasswdFile makeUploader baseURI = do
htpasswdDb <- either die return . HtPasswdDb.parse
=<< readFile htpasswdFile
concForM_ jobs htpasswdDb $ \tasks ->
httpSession "hackage-import" version $ do
setAuthorityFromURI baseURI
tasks $ \(username, mPasswdhash) ->
putUserAccount baseURI username mPasswdhash makeUploader
putUserAccount :: URI -> UserName
-> Maybe HtPasswdDb.HtPasswdHash -> Bool
-> HttpSession ()
putUserAccount baseURI username mPasswdHash makeUploader = do
do rsp <- requestPUT userURI "" LBS.empty
case rsp of
Nothing -> return ()
Just err -> fail (formatErrorResponse err)
case mPasswdHash of
Nothing -> return ()
Just (HtPasswdDb.HtPasswdHash passwdHash) -> do
rsp <- requestPUT passwdURI "text/plain" (packUTF8 passwdHash)
case rsp of
Nothing -> return ()
Just err -> fail (formatErrorResponse err)
when makeUploader $ do
rsp <- requestPUT userUploaderURI "" LBS.empty
case rsp of
Nothing -> return ()
Just err -> fail (formatErrorResponse err)
where
userURI = baseURI <//> "user" </> display username
passwdURI = userURI <//> "htpasswd"
userUploaderURI = baseURI <//> "packages/uploaders/user" </> display username
importAddresses :: Int -> FilePath -> URI -> IO ()
importAddresses jobs addressesFile baseURI = do
addressesDb <- either die return =<< UserAddressesDb.parseFile addressesFile
concForM_ jobs addressesDb $ \tasks ->
httpSession $ do
setAuthorityFromURI baseURI
tasks $ \(username, realname, email, timestamp, adminname) ->
putUserDetails baseURI username realname email timestamp adminname
putUserDetails :: URI -> UserName -> Text -> Text
-> UTCTime -> UserName -> HttpSession ()
putUserDetails baseURI username realname email timestamp adminname = do
do rsp <- requestPUT userNameAddressURI "application/json" (encode nameAddressInfo)
case rsp of
Nothing -> return ()
Just err | isErrNotFound err
-> liftIO $ info $ "Ignoring address info for user "
++ display username
Just err -> fail (formatErrorResponse err)
do now <- liftIO getCurrentTime
rsp <- requestPUT userAdminInfoURI "application/json" (encode (adminInfo now))
case rsp of
Nothing -> return ()
Just err | isErrNotFound err
-> liftIO $ info $ "Ignoring address info for user "
++ display username
Just err -> fail (formatErrorResponse err)
where
userURI = baseURI <//> "user" </> display username
userNameAddressURI = userURI <//> "name-contact.json"
userAdminInfoURI = userURI <//> "admin-info.json"
nameAddressInfo =
object
[ ("name", String realname)
, ("contactEmailAddress", String email)
]
adminInfo now =
object
[ ("accountKind", object [("AccountKindRealUser", array [])])
, ("notes", toJSON (notes now))
]
notes now = "Original hackage account created by "
++ display adminname ++ " on " ++ showUTCTime timestamp ++ "\n"
++ "Account created on this server by the hackage-import client on "
++ showUTCTime now
-------------------------------------------------------------------------------
-- Metadata command
--
data MetadataFlags = MetadataFlags {
metadataIndex :: Flag FilePath,
metadataUploadLog :: Flag FilePath,
metadataJobs :: Flag String
}
defaultMetadataFlags :: MetadataFlags
defaultMetadataFlags = MetadataFlags {
metadataIndex = NoFlag,
metadataUploadLog = NoFlag,
metadataJobs = NoFlag
}
metadataCommand :: CommandUI MetadataFlags
metadataCommand =
(makeCommand name shortDesc longDesc defaultMetadataFlags options) {
commandUsage = \pname ->
"Usage: " ++ pname ++ " " ++ name ++ " [FLAGS] [URI]\n\n"
++ "Flags for " ++ name ++ ":"
}
where
name = "metadata"
shortDesc = "Import package metadata: cabal files and upload log"
longDesc = Just $ \_ ->
"The cabal files can be imported from hackage index file,"
++ "while upload details\ncan be got from the hackage log.\n"
options _ =
[ option [] ["index"]
"Import all the packages from a hackage '00-index.tar' file"
metadataIndex (\v flags -> flags { metadataIndex = v })
(reqArgFlag "INDEX")
, option [] ["upload-log"]
"Import who uploaded what when, and set maintainer groups"
metadataUploadLog (\v flags -> flags { metadataUploadLog = v })
(reqArgFlag "LOG")
, option [] ["jobs"]
"The level of concurrency to use when uploading"
metadataJobs (\v flags -> flags { metadataJobs = v })
(reqArgFlag "N")
]
metadataAction :: MetadataFlags -> [String] -> GlobalFlags -> IO ()
metadataAction flags args _ = do
jobs <- validateOptsJobs (metadataJobs flags)
baseURI <- validateOptsServerURI args
when (metadataIndex flags == NoFlag
&& metadataUploadLog flags == NoFlag) $
die $ "specify what to import using one or more of the flags:\n"
++ " --index= --upload-log="
case metadataIndex flags of
NoFlag -> return ()
Flag file -> importIndex jobs file baseURI
case metadataUploadLog flags of
NoFlag -> return ()
Flag file -> importUploadLog jobs file baseURI
importIndex :: Int -> FilePath -> URI -> IO ()
importIndex jobs indexFile baseURI = do
info $ "Reading index file " ++ indexFile
pkgs <- either fail return
. PkgIndex.readPkgIndex
=<< LBS.readFile indexFile
pkgs' <- evaluate (sortBy (comparing fst) pkgs)
info $ "Uploading..."
concForM_ jobs pkgs' $ \tasks ->
httpSession $ do
setAuthorityFromURI baseURI
tasks $ \ (pkgid, cabalFile) ->
putCabalFile baseURI pkgid cabalFile
putCabalFile :: URI -> PackageId -> ByteString -> HttpSession ()
putCabalFile baseURI pkgid cabalFile = do
rsp <- requestPUT pkgURI "text/plain" cabalFile
case rsp of
Nothing -> return ()
Just err -> fail (formatErrorResponse err)
where
pkgURI = baseURI <//> "package" </> display pkgid
</> display (packageName pkgid) <.> "cabal"
importUploadLog :: Int -> FilePath -> URI -> IO ()
importUploadLog jobs uploadLogFile baseURI = do
info $ "Reading log file " ++ uploadLogFile
uploadLog <- either fail return
. UploadLog.read
=<< readFile uploadLogFile
let uploadInfo = UploadLog.collectUploadInfo uploadLog
maintainerInfo = UploadLog.collectMaintainerInfo uploadLog
concForM_ jobs uploadInfo $ \tasks ->
httpSession $ do
setAuthorityFromURI baseURI
tasks $ \(pkgid, time, uname) ->
putUploadInfo baseURI pkgid time uname
concForM_ jobs maintainerInfo $ \tasks ->
httpSession $ do
setAuthorityFromURI baseURI
tasks $ \(pkgname, maintainers) ->
putMaintainersInfo baseURI pkgname maintainers
putUploadInfo :: URI -> PackageId -> UTCTime -> UserName -> HttpSession ()
putUploadInfo baseURI pkgid time uname = do
liftIO $ info $ "setting upload info for " ++ display pkgid
do let timeStr = showUTCTime time
rsp <- requestPUT (pkgURI <//> "upload-time") "text/plain" (packUTF8 timeStr)
case rsp of
Nothing -> return ()
Just err | isErrNotFound err -> liftIO $ info $ "Ignoring upload log entry for package " ++ display pkgid
Just err -> fail (formatErrorResponse err)
do let nameStr = display uname
rsp <- requestPUT (pkgURI <//> "uploader") "text/plain" (packUTF8 nameStr)
case rsp of
Nothing -> return ()
Just err | isErrNotFound err -> liftIO $ info $ "Ignoring upload log entry for package " ++ display pkgid
Just err -> fail (formatErrorResponse err)
where
pkgURI = baseURI <//> "package" </> display pkgid
putMaintainersInfo :: URI -> PackageName -> [UserName] -> HttpSession ()
putMaintainersInfo baseURI pkgname maintainers =
-- Add to the package's maintainers group
forM_ maintainers $ \uname -> do
rsp <- requestPUT (pkgURI <//> "maintainers" </> "user" </> display uname) "" LBS.empty
case rsp of
Nothing -> return ()
Just err | isErrNotFound err -> liftIO $ info $ "Cannot make " ++ display uname ++ " a maintainer for package " ++ display pkgname
Just err -> fail (formatErrorResponse err)
where
pkgURI = baseURI <//> "package" </> display pkgname
-------------------------------------------------------------------------------
-- Tarballs command
--
data TarballFlags = TarballFlags {
tarballJobs :: Flag String
}
defaultTarballFlags :: TarballFlags
defaultTarballFlags = TarballFlags {
tarballJobs = NoFlag
}
tarballCommand :: CommandUI TarballFlags
tarballCommand =
(makeCommand name shortDesc longDesc defaultTarballFlags options) {
commandUsage = \pname ->
"Usage: " ++ pname ++ " " ++ name ++ " [URI] [TARBALL]... \n\n"
++ "Flags for " ++ name ++ ":"
}
where
name = "tarball"
shortDesc = "Import package tarballs"
longDesc = Just $ \_ ->
"The package tarballs can be imported directly from\n"
++ " local .tar.gz files.\n"
options _ = [ option [] ["jobs"]
"The level of concurrency to use when uploading tarballs"
tarballJobs (\v flags -> flags { tarballJobs = v })
(reqArgFlag "N")
]
tarballAction :: TarballFlags -> [String] -> GlobalFlags -> IO ()
tarballAction flags args _ = do
jobs <- validateOptsJobs (tarballJobs flags)
(baseURI, tarballFiles) <- validateOptsServerURI' args
let pkgidAndTarball =
[ (mpkgid, file)
| file <- tarballFiles
, let pkgidstr = (dropExtension . dropExtension . takeFileName) file
ext = takeExtension (dropExtension file)
<.> takeExtension file
mpkgid | ext == ".tar.gz"
, Just pkgid <- simpleParse pkgidstr
, null (versionTags (packageVersion pkgid))
= Just pkgid
| otherwise
= Nothing
]
case [ file | (Nothing, file) <- pkgidAndTarball] of
[] -> return ()
files -> warn normal $ "the following files will be ignored because they "
++ "do not match the expected naming convention of "
++ "foo-1.0.tar.gz:\n" ++ unlines files
let pkgidAndTarball' = [ (pkgid, tarballFilePath)
| (Just pkgid, tarballFilePath) <- pkgidAndTarball ]
concForM_ jobs pkgidAndTarball' $ \tasks ->
httpSession $ do
setAuthorityFromURI baseURI
tasks $ \(pkgid, tarballFilePath) ->
putPackageTarball baseURI pkgid tarballFilePath
putPackageTarball :: URI -> PackageId -> FilePath -> HttpSession ()
putPackageTarball baseURI pkgid tarballFilePath = do
pkgContent <- liftIO $ LBS.readFile tarballFilePath
rsp <- requestPUT pkgURI "application/x-gzip" pkgContent
case rsp of
Nothing -> return ()
Just err -> out (formatErrorResponse err)
where
pkgURI = baseURI <//> "package" </> display pkgid </> display pkgid <.> "tar.gz"
-------------------------------------------------------------------------------
-- Deprecations command
--
data DeprecationFlags = DeprecationFlags
defaultDeprecationFlags :: DeprecationFlags
defaultDeprecationFlags = DeprecationFlags
deprecationCommand :: CommandUI DeprecationFlags
deprecationCommand =
(makeCommand name shortDesc longDesc defaultDeprecationFlags options) {
commandUsage = \pname ->
"Usage: " ++ pname ++ " " ++ name ++ " [URI] [TAGS]... \n\n"
++ "Flags for " ++ name ++ ":"
}
where
name = "deprecation"
shortDesc = "Import package deprecation info from old hackage files"
longDesc = Just $ \_ ->
"The old hackage server has files like alsa/0.4/tags\n"
++ "and some of these tags files contain info about the \n"
++ "package being deprecated, and sometimes what it is\n"
++ "superceded by. The files must follow this file name\n"
++ "convention so we know which package the tags apply to.\n"
options _ = []
deprecationAction :: DeprecationFlags -> [String] -> GlobalFlags -> IO ()
deprecationAction _flags args _ = do
(baseURI, tagFiles) <- validateOptsServerURI' args
entries <- forM tagFiles $ \tagFile -> do
content <- readFile tagFile
either die return (TagsFile.read tagFile content)
httpSession $ do
setAuthorityFromURI baseURI
sequence_
[ putDeprecatedInfo baseURI pkgname replacement
| (pkgname, replacement) <- TagsFile.collectDeprecated entries ]
putDeprecatedInfo :: URI -> PackageName -> Maybe PackageName -> HttpSession ()
putDeprecatedInfo baseURI pkgname replacement = do
rsp <- requestPUT (pkgURI <//> "deprecated.json") "application/json" (encode deprecatedInfo)
case rsp of
Nothing -> return ()
Just err -> fail (formatErrorResponse err)
where
pkgURI = baseURI <//> "package" </> display pkgname
deprecatedInfo =
object
[ ("is-deprecated", Bool True)
, ("in-favour-of", array [ string $ display pkg
| pkg <- maybeToList replacement ])
]
-------------------------------------------------------------------------------
-- Distro command
--
data DistroFlags = DistroFlags
defaultDistroFlags :: DistroFlags
defaultDistroFlags = DistroFlags
distroCommand :: CommandUI DistroFlags
distroCommand =
(makeCommand name shortDesc longDesc defaultDistroFlags options) {
commandUsage = \pname ->
"Usage: " ++ pname ++ " " ++ name ++ " [URI] [TAGS]... \n\n"
++ "Flags for " ++ name ++ ":"
}
where
name = "distro"
shortDesc = "Import distro info from old hackage files"
longDesc = Just $ \_ ->
"The old hackage server has files like archive/00-distromap/Debian\n"
++ "which contain info about what versions of the packages \n"
++ "are available in the respective distributions.\n"
++ "The file name must be the distro name."
options _ = []
distroAction :: DistroFlags -> [String] -> GlobalFlags -> IO ()
distroAction _flags args _ = do
(baseURI, distroFiles) <- validateOptsServerURI' args
distros <- forM distroFiles $ \distroFile -> do
content <- readFile distroFile
let (errs, entries) = DistroMap.read content
mapM_ info errs
return (takeFileName distroFile, entries)
httpSession $ do
setAuthorityFromURI baseURI
sequence_
[ putDistroInfo baseURI distroname entries
| (distroname, entries) <- distros, not (null entries) ]
putDistroInfo :: URI -> String -> [DistroMap.Entry] -> HttpSession ()
putDistroInfo baseURI distroname entries = do
do rsp <- requestPUT distroURI "" LBS.empty
case rsp of
Nothing -> return ()
Just err -> fail (formatErrorResponse err)
do rsp <- requestPUT (distroURI <//> "packages.csv") "text/csv" (toBS entries)
case rsp of
Nothing -> return ()
Just err -> fail (formatErrorResponse err)
where
distroURI = baseURI <//> "distro" </> distroname
toBS = packUTF8 . CSV.printCSV . DistroMap.toCSV
-------------------------------------------------------------------------------
-- Documentation tarballs command
--
data DocsFlags = DocsFlags {
docsJobs :: Flag String
}
defaultDocsFlags :: DocsFlags
defaultDocsFlags = DocsFlags {
docsJobs = NoFlag
}
docsCommand :: CommandUI DocsFlags
docsCommand =
(makeCommand name shortDesc longDesc defaultDocsFlags options) {
commandUsage = \pname ->
"Usage: " ++ pname ++ " " ++ name ++ " [URI] [TARBALL]... \n\n"
++ "Flags for " ++ name ++ ":"
}
where
name = "docs"
shortDesc = "Import package documentation tarballs"
longDesc = Just $ \_ ->
"The package documentation can be imported directly from\n"
++ " local .tar or .tar.gz files of the html bundle."
options _ = [ option [] ["jobs"]
"The level of concurrency to use when uploading documentation"
docsJobs (\v flags -> flags { docsJobs = v })
(reqArgFlag "N")
]
docsAction :: DocsFlags -> [String] -> GlobalFlags -> IO ()
docsAction flags args _ = do
jobs <- validateOptsJobs (docsJobs flags)
(baseURI, docTarballFiles) <- validateOptsServerURI' args
let pkgidAndTarball =
[ (mpkgid, file)
| file <- docTarballFiles
, let pkgidstr = (dropExtension . dropExtension. takeFileName) file
ext = takeExtension (dropExtension file)
<.> takeExtension file
mpkgid | ext == ".tar" || ext == ".tar.gz"
, Just pkgid <- simpleParse pkgidstr
, versionTags (packageVersion pkgid) == ["docs"]
= Just pkgid
| otherwise
= Nothing
]
case [ file | (Nothing, file) <- pkgidAndTarball ] of
[] -> return ()
files -> warn normal $ "the following files don't match the expected naming "
++ "convention of foo-1.0-docs.tar[.gz]:\n" ++ unlines files
let pkgidAndTarball' = [ (pkgid, tarballFilePath)
| (Just pkgid, tarballFilePath) <- pkgidAndTarball ]
concForM_ jobs pkgidAndTarball' $ \tasks ->
httpSession $ do
setAuthorityFromURI baseURI
tasks $ \(pkgid, tarballFilePath) ->
putPackageDocsTarball baseURI pkgid tarballFilePath
putPackageDocsTarball :: URI -> PackageId -> FilePath -> HttpSession ()
putPackageDocsTarball baseURI pkgid tarballFilePath = do
tarballContent <- liftIO $ LBS.readFile tarballFilePath
let extraHeaders
| takeExtension tarballFilePath == ".gz"
= [Header HdrContentEncoding "gzip"]
| otherwise = []
rsp <- requestPUTWithHeaders pkgDocURI "application/x-tar" extraHeaders
tarballContent
case rsp of
Nothing -> return ()
Just err | isErrNotFound err
-> liftIO $ info $ "Ignoring documentation for package "
++ display pkgid
Just err -> fail (formatErrorResponse err)
where
pkgDocURI = baseURI <//> "package" </> display pkgid </> "docs.tar"
-------------------------------------------------------------------------------
-- Download count command
--
data DownloadCountFlags = DownloadCountFlags
defaultDownloadCountFlags :: DownloadCountFlags
defaultDownloadCountFlags = DownloadCountFlags
downloadCountCommand :: CommandUI DownloadCountFlags
downloadCountCommand =
(makeCommand name shortDesc longDesc defaultDownloadCountFlags options) {
commandUsage = \pname ->
"Usage: " ++ pname ++ " " ++ name ++ " URI [LOG.GZ]... \n\n"
++ "Flags for " ++ name ++ ":"
}
where
name = "downloads"
shortDesc = "Import download counts"
longDesc = Just $ \_ -> unlines $ [
"Replace the on-disk download statistics with the download statistics"
, "extracted from Apache log files (in .gz format)"
]
options _ = []
downloadCountAction :: DownloadCountFlags -> [String] -> GlobalFlags -> IO ()
downloadCountAction _ args _ = do
(baseURI, logFiles) <- validateOptsServerURI' args
csv <- logToDownloadCounts <$> readLogs logFiles
-- Compute before we open the connection to the server
evaluate $ LBS.length csv
httpSession $ do
setAuthorityFromURI baseURI
void $ requestPUT (baseURI <//> "packages" </> "downloads.csv") "text/csv" csv
where
readLogs :: [FilePath] -> IO LBS.ByteString
readLogs paths = LBS.concat <$> mapM decompress paths
decompress :: FilePath -> IO LBS.ByteString
decompress path = GZip.decompressNamed path <$> LBS.readFile path
-------------------------
-- HTTP utilities
-------------------------
infixr 5 <//>
(<//>) :: URI -> FilePath -> URI
uri <//> path = uri { uriPath = Posix.addTrailingPathSeparator (uriPath uri)
Posix.</> escapeURIString isUnescapedInURI path }
validateHttpURI :: String -> Either String URI
validateHttpURI str = case parseURI str of
Nothing -> Left ("invalid URL " ++ str)
Just uri
| uriScheme uri /= "http:" -> Left ("only http URLs are supported " ++ str)
| isNothing (uriAuthority uri) -> Left ("server name required in URL " ++ str)
| otherwise -> Right uri
type HttpSession a = BrowserAction (HandleStream ByteString) a
httpSession :: HttpSession a -> IO a
httpSession action =
browse $ do
setUserAgent ("hackage-import/" ++ display Paths.version)
setErrHandler (warn verbosity)
setOutHandler (debug verbosity)
setAllowBasicAuth True
setCheckForProxy True
action
where
verbosity = normal
data ErrorResponse = ErrorResponse URI ResponseCode String (Maybe String)
deriving Show
isErrNotFound :: ErrorResponse -> Bool
isErrNotFound (ErrorResponse _ (4,0,4) _ _) = True
isErrNotFound _ = False
-- | We can do http digest auth, however currently the Network.Browser module
-- does not cache the auth info so it has to re-auth for every single request.
-- So instead here we just make it pre-emptively supply basic auth info.
-- We assume this is fine since we're probably working with localhost anyway.
--
setAuthorityFromURI :: URI -> HttpSession ()
setAuthorityFromURI uri
| Just (username, passwd) <- extractCredentials uri
= addAuthority AuthBasic {
auRealm = "Hackage",
auUsername = username,
auPassword = passwd,
auSite = uri
}
| otherwise = return ()
extractCredentials :: URI -> Maybe (String, String)
extractCredentials uri
| Just authority <- uriAuthority uri
, (username, ':':passwd0) <- break (==':') (uriUserInfo authority)
, let passwd = takeWhile (/='@') passwd0
, not (null username)
, not (null passwd)
= Just (username, passwd)
extractCredentials _ = Nothing
requestGET :: URI -> HttpSession (Either ErrorResponse ByteString)
requestGET uri = do
(_, rsp) <- request (Request uri GET headers LBS.empty)
case rspCode rsp of
(2,0,0) -> return (Right (rspBody rsp))
_ -> return (Left (mkErrorResponse uri rsp))
where
headers = []
requestPUT :: URI -> String -> ByteString -> HttpSession (Maybe ErrorResponse)
requestPUT uri mimetype body =
let extraHeaders = [] in
requestPUTWithHeaders uri mimetype extraHeaders body
requestPUTWithHeaders :: URI -> String -> [Header] -> ByteString
-> HttpSession (Maybe ErrorResponse)
requestPUTWithHeaders uri mimetype extraHeaders body = do
(_, rsp) <- request (Request uri PUT headers body)
case rspCode rsp of
(2,_,_) -> return Nothing
_ -> return (Just (mkErrorResponse uri rsp))
where
headers = Header HdrContentLength (show (LBS.length body))
: Header HdrContentType mimetype
: extraHeaders
mkErrorResponse :: URI -> Response ByteString -> ErrorResponse
mkErrorResponse uri rsp =
ErrorResponse uri (rspCode rsp) (rspReason rsp) mBody
where
mBody = case lookupHeader HdrContentType (rspHeaders rsp) of
Just mimetype | "text/plain" `isPrefixOf` mimetype
-> Just (unpackUTF8 (rspBody rsp))
_ -> Nothing
formatErrorResponse :: ErrorResponse -> String
formatErrorResponse (ErrorResponse uri (a,b,c) reason mBody) =
"HTTP error code " ++ show a ++ show b ++ show c
++ ", " ++ reason ++ "\n " ++ show uri
++ maybe "" (('\n':) . unlines . map (" "++) . lines . wrapText) mBody
-------------------------------------------------------------------------------
-- Utils
--
showUTCTime :: UTCTime -> String
showUTCTime = formatTime defaultTimeLocale "%c"
-- option utility
reqArgFlag :: ArgPlaceHolder -> SFlags -> LFlags -> Description
-> (a -> Flag String) -> (Flag String -> a -> a)
-> OptDescr a
reqArgFlag ad = reqArg' ad Flag flagToList
warn :: Verbosity -> String -> IO ()
warn verbosity msg =
when (verbosity >= normal) $
putStrLn ("Warning: " ++ msg)
debug :: Verbosity -> String -> IO ()
debug verbosity msg =
when (verbosity > normal) $
putStrLn ("Debug: " ++ msg)
info :: String -> IO ()
info msg = do
pname <- getProgName
putStrLn (pname ++ ": " ++ msg)
hFlush stdout
validateOptsServerURI :: [String] -> IO URI
validateOptsServerURI [server] = either die return $ validateHttpURI server
validateOptsServerURI _ = die $ "The command expects the target server "
++ "URI e.g. http://admin:admin@localhost:8080/"
validateOptsServerURI' :: [String] -> IO (URI, [String])
validateOptsServerURI' (server:opts) = do uri <- either die return $ validateHttpURI server
return (uri,opts)
validateOptsServerURI' _ = die $ "The command expects the target server "
++ "URI e.g. http://admin:admin@localhost:8080/"
validateOptsJobs :: Flag String -> IO Int
validateOptsJobs NoFlag = return 1
validateOptsJobs (Flag s)
| [(n,"")] <- reads s
, n >= 1 && n <= 16 = return n
validateOptsJobs (Flag s)
| [(_ :: Int,"")] <- reads s = die "not a sensible number for --jobs"
| otherwise = die "expected a number for --jobs"
-------------------------------------------------------------------------------
-- Concurrency Utils
--
concForM_ :: MonadIO m => Int -> [a] -> (((a -> m ()) -> m ()) -> IO ()) -> IO ()
concForM_ n = flip (concMapM_ n)
concMapM_ :: forall m a. MonadIO m => Int -> (((a -> m ()) -> m ()) -> IO ()) -> [a] -> IO ()
concMapM_ n action xs = do
chan <- newChan
writeList2Chan chan (map Just xs ++ replicate n Nothing)
bracket
(replicateM n (async (worker chan)))
(mapM_ cancel)
(\as -> waitAny as >> mapM_ wait as)
where