]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
Improve task management to use blocking wait if possible
[builder.git] / source / builder.cpp
1 #include <set>
2 #include <msp/core/getopt.h>
3 #include <msp/datafile/parser.h>
4 #include <msp/fs/dir.h>
5 #include <msp/fs/stat.h>
6 #include <msp/fs/utils.h>
7 #include <msp/io/buffered.h>
8 #include <msp/io/file.h>
9 #include <msp/io/print.h>
10 #include <msp/strings/format.h>
11 #include <msp/strings/regex.h>
12 #include <msp/strings/utils.h>
13 #include <msp/time/units.h>
14 #include <msp/time/utils.h>
15 #include "analyzer.h"
16 #include "binarypackage.h"
17 #include "builder.h"
18 #include "copy.h"
19 #include "gnuarchiver.h"
20 #include "gnuccompiler.h"
21 #include "gnucxxcompiler.h"
22 #include "gnulinker.h"
23 #include "installedfile.h"
24 #include "package.h"
25 #include "pkgconfiggenerator.h"
26 #include "sharedlibrary.h"
27 #include "sourcepackage.h"
28 #include "tar.h"
29 #include "task.h"
30 #include "virtualtarget.h"
31
32 using namespace std;
33 using namespace Msp;
34
35 Builder::Builder(int argc, char **argv):
36         package_manager(*this),
37         main_pkg(0),
38         native_arch(*this, string()),
39         build_type(0),
40         vfs(*this),
41         analyzer(0),
42         build(false),
43         clean(0),
44         dry_run(false),
45         help(false),
46         show_progress(false),
47         build_file("Build"),
48         jobs(1),
49         conf_all(false),
50         conf_only(false),
51         build_all(false),
52         create_makefile(false),
53         tempdir("temp")
54 {
55         string analyze_mode;
56         string work_dir;
57         bool full_paths = false;
58         unsigned max_depth = 5;
59         StringList cmdline_warn;
60         string prfx;
61         string temp_str;
62         string arch;
63         bool no_externals = false;
64         unsigned verbose = 1;
65         bool silent = false;
66         list<string> log_channels;
67         string build_type_name;
68
69         GetOpt getopt;
70         getopt.add_option('a', "analyze",    analyze_mode,  GetOpt::REQUIRED_ARG).set_help("Perform analysis.  MODE can be deps, alldeps or rebuild.", "MODE");
71         getopt.add_option('b', "build",      build,         GetOpt::NO_ARG).set_help("Perform build even if doing analysis.");
72         getopt.add_option('c', "clean",      clean,         GetOpt::NO_ARG).set_help("Clean buildable targets.");
73         getopt.add_option('f', "file",       build_file,    GetOpt::REQUIRED_ARG).set_help("Read info from FILE instead of Build.", "FILE");
74         getopt.add_option('h', "help",       help,          GetOpt::NO_ARG).set_help("Print this message.");
75         getopt.add_option('j', "jobs",       jobs,          GetOpt::REQUIRED_ARG).set_help("Run NUM commands at once, whenever possible.", "NUM");
76         getopt.add_option('l', "log",        log_channels,  GetOpt::REQUIRED_ARG).set_help("Set log channels to be displayed.", "LIST");
77         getopt.add_option('n', "dry-run",    dry_run,       GetOpt::NO_ARG).set_help("Don't actually do anything, only show what would be done.");
78         getopt.add_option('s', "silent",     silent,        GetOpt::NO_ARG).set_help("Don't print any messages other than errors.");
79         getopt.add_option('t', "build-type", build_type_name, GetOpt::REQUIRED_ARG).set_help("Set build type.", "TYPE");
80         getopt.add_option('v', "verbose",    verbose,       GetOpt::NO_ARG).set_help("Print more information about what's going on.");
81         getopt.add_option('x', "no-externals",  no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
82         getopt.add_option('A', "conf-all",   conf_all,      GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
83         getopt.add_option('B', "build-all",  build_all,     GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
84         getopt.add_option('C', "chdir",      work_dir,      GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
85         getopt.add_option('P', "progress",   show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
86         getopt.add_option('W', "what-if",    what_if,       GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
87         getopt.add_option(     "arch",       arch,          GetOpt::REQUIRED_ARG).set_help("Build for architecture ARCH.", "ARCH");
88         getopt.add_option(     "conf-only",  conf_only,     GetOpt::NO_ARG).set_help("Stop after configuring packages.");
89         getopt.add_option(     "full-paths", full_paths,    GetOpt::NO_ARG).set_help("Output full paths in analysis.");
90         getopt.add_option(     "max-depth",  max_depth,     GetOpt::REQUIRED_ARG).set_help("Show up to NUM levels in analysis..", "NUM");
91         getopt.add_option(     "prefix",     prfx,          GetOpt::REQUIRED_ARG).set_help("Install things to DIR.", "DIR");
92         getopt.add_option(     "tempdir",    temp_str,      GetOpt::REQUIRED_ARG).set_help("Store temporary files in DIR.", "DIR");
93         usagemsg = getopt.generate_usage(argv[0])+" [<target> ...]";
94         helpmsg = getopt.generate_help();
95         getopt(argc, argv);
96
97         if(silent)
98                 --verbose;
99         if(verbose>=1)
100         {
101                 logger.enable_channel("summary");
102                 logger.enable_channel("tasks");
103         }
104         if(verbose>=2)
105         {
106                 logger.enable_channel("environment");
107                 logger.enable_channel("packages");
108                 logger.enable_channel("commands");
109         }
110         if(verbose>=3)
111         {
112                 logger.enable_channel("packagemgr");
113                 logger.enable_channel("configure");
114         }
115         if(verbose>=4)
116         {
117                 logger.enable_channel("files");
118                 logger.enable_channel("auxcommands");
119         }
120         if(verbose>=5)
121         {
122                 logger.enable_channel("tools");
123                 logger.enable_channel("vfs");
124         }
125         for(list<string>::const_iterator i=log_channels.begin(); i!=log_channels.end(); ++i)
126         {
127                 vector<string> parts = split(*i, ',');
128                 for(vector<string>::const_iterator j=parts.begin(); j!=parts.end(); ++j)
129                         logger.enable_channel(*j);
130         }
131
132         if(!analyze_mode.empty())
133         {
134                 analyzer = new Analyzer(*this);
135
136                 if(analyze_mode=="deps")
137                         analyzer->set_mode(Analyzer::DEPS);
138                 else if(analyze_mode=="alldeps")
139                         analyzer->set_mode(Analyzer::ALLDEPS);
140                 else if(analyze_mode=="rebuild")
141                         analyzer->set_mode(Analyzer::REBUILD);
142                 else if(analyze_mode=="rdeps")
143                         analyzer->set_mode(Analyzer::RDEPS);
144                 else
145                         throw usage_error("Invalid analyze mode");
146
147                 analyzer->set_max_depth(max_depth);
148                 analyzer->set_full_paths(full_paths);
149         }
150         else if(!clean && !create_makefile)
151                 build = true;
152
153         const vector<string> &args = getopt.get_args();
154         for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
155         {
156                 string::size_type equal = i->find('=');
157                 if(equal!=string::npos)
158                         cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
159                 else
160                         cmdline_targets.push_back(*i);
161         }
162
163         if(cmdline_targets.empty())
164                 cmdline_targets.push_back("default");
165
166         if(!work_dir.empty())
167                 FS::chdir(work_dir);
168
169         cwd = FS::getcwd();
170
171         package_manager.set_no_externals(no_externals);
172
173         if(arch.empty())
174                 current_arch = &native_arch;
175         else
176                 current_arch = new Architecture(*this, arch);
177
178         load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
179         load_build_file((FS::get_user_data_dir("builder")/"rc").str());
180
181         if(prfx.empty())
182         {
183                 if(current_arch->is_native())
184                         prefix = (FS::get_home_dir()/"local").str();
185                 else
186                         prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
187         }
188         else
189                 prefix = cwd/prfx;
190
191         if(!temp_str.empty())
192                 tempdir = temp_str;
193
194         if(!build_type_name.empty())
195         {
196                 BuildTypeMap::iterator i = build_types.find(build_type_name);
197                 if(i==build_types.end())
198                         throw usage_error("Unknown build type");
199                 build_type = &i->second;
200         }
201
202         toolchain.add_tool(new GnuCCompiler(*this, *current_arch));
203         toolchain.add_tool(new GnuCxxCompiler(*this, *current_arch));
204         toolchain.add_tool(new GnuLinker(*this, *current_arch));
205         toolchain.add_tool(new GnuArchiver(*this, *current_arch));
206         toolchain.add_tool(new Copy(*this));
207         toolchain.add_tool(new Tar(*this));
208         toolchain.add_tool(new PkgConfigGenerator(*this));
209 }
210
211 Builder::~Builder()
212 {
213         for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
214                 delete i->second;
215         delete analyzer;
216 }
217
218 int Builder::main()
219 {
220         if(load_build_file(cwd/build_file))
221         {
222                 if(help)
223                 {
224                         usage(0, "builder", false);
225                         return 0;
226                 }
227                 else
228                 {
229                         IO::print(IO::cerr, "No build info here.\n");
230                         return 1;
231                 }
232         }
233
234         if(help)
235         {
236                 usage(0, "builder", false);
237                 IO::print("\n");
238                 package_help();
239                 return 0;
240         }
241
242         if(!prepare_build())
243                 return 1;
244
245         if(conf_only)
246                 return 0;
247
248         logger.log("environment", format("Building on %s, for %s%s", native_arch.get_name(),
249                 current_arch->get_name(), (current_arch->is_native() ? " (native)" : "")));
250         logger.log("environment", format("Prefix is %s", prefix));
251         if(tempdir.is_absolute())
252                 logger.log("environment", format("Temporary directory is %s", tempdir));
253         else
254                 logger.log("environment", format("Using per-package temporary directory %s", tempdir));
255         if(build_type)
256                 logger.log("environment", format("Build type is %s", build_type->get_name()));
257
258         const PackageManager::PackageMap &packages = package_manager.get_packages();
259         list<string> package_details;
260         for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
261         {
262                 if(!i->second || !i->second->is_prepared())
263                         continue;
264
265                 string line = i->second->get_name();
266                 if(dynamic_cast<SourcePackage *>(i->second))
267                 {
268                         line += '*';
269
270                         unsigned count = 0;
271                         unsigned to_be_built = 0;
272                         for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
273                                 if(j->second->get_package()==i->second)
274                                 {
275                                         ++count;
276                                         if(j->second->needs_rebuild())
277                                                 ++to_be_built;
278                                 }
279                         if(count)
280                         {
281                                 line += format(" (%d targets", count);
282                                 if(to_be_built)
283                                         line += format(", %d to be built", to_be_built);
284                                 line += ')';
285                         }
286                 }
287
288                 package_details.push_back(line);
289         }
290
291         logger.log("summary", format("%d active packages, %d targets", package_details.size(), targets.size()));
292         for(list<string>::const_iterator i=package_details.begin(); i!=package_details.end(); ++i)
293                 logger.log("packages", *i);
294
295         if(analyzer)
296                 analyzer->analyze();
297
298         if(!problems.empty())
299         {
300                 IO::print(IO::cerr, "The following problems were detected:\n");
301                 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
302                         IO::print(IO::cerr, "  %s: %s\n", i->package, i->descr);
303                 if(!analyzer)
304                         IO::print(IO::cerr, "Please fix them and try again.\n");
305                 return 1;
306         }
307
308         if(clean)
309                 exit_code = do_clean();
310         else if(build)
311                 exit_code = do_build();
312
313         return exit_code;
314 }
315
316 Target *Builder::get_target(const string &n) const
317 {
318         TargetMap::const_iterator i = targets.find(n);
319         if(i!=targets.end())
320                 return i->second;
321         return 0;
322 }
323
324 void Builder::problem(const string &p, const string &d)
325 {
326         problems.push_back(Problem(p, d));
327 }
328
329 void Builder::add_target(Target *t)
330 {
331         targets.insert(TargetMap::value_type(t->get_name(), t));
332 }
333
334 void Builder::add_primary_target(Target &t)
335 {
336         get_target("world")->add_dependency(t);
337
338         if(t.get_package()==main_pkg && t.get_component() && t.get_component()->is_default())
339                 get_target("default")->add_dependency(t);
340 }
341
342 void Builder::usage(const char *reason, const char *argv0, bool brief)
343 {
344         if(reason)
345                 IO::print(IO::cerr, "%s\n", reason);
346
347         if(brief)
348                 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
349         else
350         {
351                 IO::print(IO::cerr, "Builder 1.0\n\n");
352                 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
353                 IO::print(IO::cerr, "Options:\n");
354                 IO::print(IO::cerr, helpmsg);
355         }
356 }
357
358 int Builder::load_build_file(const FS::Path &fn)
359 {
360         if(!FS::exists(fn))
361                 return -1;
362
363         IO::BufferedFile in(fn.str());
364
365         logger.log("files", format("Reading %s", fn));
366
367         DataFile::Parser parser(in, fn.str());
368         Loader loader(*this);
369         loader.load(parser);
370
371         return 0;
372 }
373
374 bool Builder::prepare_build()
375 {
376         Target *world = new VirtualTarget(*this, "world");
377
378         Target *def_tgt = new VirtualTarget(*this, "default");
379         world->add_dependency(*def_tgt);
380
381         Target *install = new VirtualTarget(*this, "install");
382         world->add_dependency(*install);
383
384         Target *tarballs = new VirtualTarget(*this, "tarballs");
385         world->add_dependency(*tarballs);
386
387         main_pkg->prepare();
388
389         // Make the cmdline target depend on all targets mentioned on the command line
390         Target *cmdline = new VirtualTarget(*this, "cmdline");
391         for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
392         {
393                 Target *tgt = get_target(*i);
394                 if(!tgt)
395                         tgt = vfs.get_target(*i);
396                 if(!tgt)
397                         tgt = vfs.get_target(cwd/ *i);
398                 if(!tgt)
399                 {
400                         IO::print("I don't know anything about %s\n", *i);
401                         return false;
402                 }
403
404                 cmdline->add_dependency(*tgt);
405         }
406
407         cmdline->prepare();
408
409         // Apply what-ifs
410         for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
411         {
412                 FileTarget *tgt = vfs.get_target(cwd/ *i);
413                 if(!tgt)
414                 {
415                         IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
416                         return false;
417                 }
418                 tgt->touch();
419         }
420
421         if(build_all)
422         {
423                 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
424                         if(i->second->is_buildable() && !i->second->needs_rebuild())
425                                 i->second->force_rebuild();
426         }
427
428         if(!dry_run)
429         {
430                 const PackageManager::PackageMap &packages = package_manager.get_packages();
431                 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
432                         i->second->save_caches();
433         }
434
435         return true;
436 }
437
438 int Builder::do_build()
439 {
440         Target *cmdline = get_target("cmdline");
441
442         unsigned total = 0;
443         for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
444                 if(i->second->is_buildable() && i->second->needs_rebuild())
445                         ++total;
446
447         if(!total)
448         {
449                 logger.log("summary", "Already up to date");
450                 return 0;
451         }
452         logger.log("summary", format("Will build %d target%s", total, (total!=1 ? "s" : "")));
453
454         vector<Task *> tasks;
455
456         unsigned count = 0;
457
458         bool fail = false;
459         bool finish = false;
460         bool starved = false;
461
462         while(!finish)
463         {
464                 if(tasks.size()<jobs && !fail && !starved)
465                 {
466                         Target *tgt = cmdline->get_buildable_target();
467                         if(tgt)
468                         {
469                                 if(tgt->get_tool())
470                                         logger.log("tasks", format("%-4s  %s", tgt->get_tool()->get_tag(), tgt->get_name()));
471                                 Task *task = tgt->build();
472                                 if(task)
473                                 {
474                                         logger.log("commands", format("%s", task->get_command()));
475                                         if(dry_run)
476                                         {
477                                                 task->signal_finished.emit(true);
478                                                 delete task;
479                                         }
480                                         else
481                                         {
482                                                 task->start();
483                                                 tasks.push_back(task);
484                                         }
485                                 }
486
487                                 if(show_progress)
488                                         IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
489                         }
490                         else if(tasks.empty())
491                                 finish = true;
492                         else
493                                 starved = true;
494                 }
495                 else
496                         Time::sleep(10*Time::msec);
497
498                 for(unsigned i=0; i<tasks.size();)
499                 {
500                         Task::Status status;
501                         if(jobs==1 || (tasks.size()==1 && starved))
502                                 status = tasks[i]->wait();
503                         else
504                                 status = tasks[i]->check();
505
506                         if(status!=Task::RUNNING)
507                         {
508                                 ++count;
509
510                                 delete tasks[i];
511                                 tasks.erase(tasks.begin()+i);
512                                 if(status==Task::ERROR)
513                                         fail = true;
514                                 if(tasks.empty() && fail)
515                                         finish = true;
516                                 starved = false;
517                         }
518                         else
519                                 ++i;
520                 }
521         }
522
523         if(show_progress)
524                 IO::print("\033[K");
525         if(fail)
526                 logger.log("summary", "Build failed");
527         else if(show_progress)
528                 logger.log("summary", "Build complete");
529
530         if(!dry_run)
531         {
532                 const PackageManager::PackageMap &packages = package_manager.get_packages();
533                 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
534                         i->second->save_caches();
535         }
536
537         return fail;
538 }
539
540 int Builder::do_clean()
541 {
542         // Cleaning doesn't care about ordering, so a simpler method can be used
543
544         set<Target *> clean_tgts;
545         list<Target *> queue;
546         queue.push_back(get_target("cmdline"));
547
548         while(!queue.empty())
549         {
550                 Target *tgt = queue.front();
551                 queue.erase(queue.begin());
552
553                 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
554                         clean_tgts.insert(tgt);
555
556                 const Target::Dependencies &deps = tgt->get_dependencies();
557                 for(list<Target *>::const_iterator i=deps.begin(); i!=deps.end(); ++i)
558                         if(!clean_tgts.count(*i))
559                                 queue.push_back(*i);
560         }
561
562         for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
563                 if(FileTarget *ft = dynamic_cast<FileTarget *>(*i))
564                         if(ft->get_mtime())
565                                 FS::unlink(ft->get_path());
566
567         return 0;
568 }
569
570 void Builder::package_help()
571 {
572         const Config &config = main_pkg->get_config();
573         const Config::OptionMap &options = config.get_options();
574
575         IO::print("Required packages:\n  ");
576         const PackageList &requires = main_pkg->get_required_packages();
577         for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
578         {
579                 if(i!=requires.begin())
580                         IO::print(", ");
581                 IO::print((*i)->get_name());
582         }
583         IO::print("\n\nPackage configuration:\n");
584         for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
585         {
586                 const Config::Option &opt = i->second;
587                 IO::print("  %s: %s (%s)", opt.name, opt.description, opt.value);
588                 if(opt.value!=opt.default_value)
589                         IO::print(" [%s]", opt.default_value);
590                 IO::print("\n");
591         }
592 }
593
594 string Builder::usagemsg;
595 string Builder::helpmsg;
596
597
598 Builder::Loader::Loader(Builder &b):
599         DataFile::ObjectLoader<Builder>(b)
600 {
601         add("architecture", &Loader::architecture);
602         add("binary_package", &Loader::binpkg);
603         add("build_type", &Loader::build_type);
604         add("profile", &Loader::profile);
605         add("package", &Loader::package);
606 }
607
608 void Builder::Loader::architecture(const string &n)
609 {
610         if(obj.current_arch->match_name(n))
611                 load_sub(*obj.current_arch);
612 }
613
614 void Builder::Loader::binpkg(const string &n)
615 {
616         BinaryPackage *pkg = new BinaryPackage(obj, n);
617         load_sub(*pkg);
618 }
619
620 void Builder::Loader::build_type(const string &n)
621 {
622         BuildType btype(n);
623         load_sub(btype);
624         BuildTypeMap::iterator i = obj.build_types.insert(BuildTypeMap::value_type(n, btype)).first;
625         if(!obj.build_type)
626                 obj.build_type = &i->second;
627 }
628
629 void Builder::Loader::profile(const string &)
630 {
631         IO::print("Profiles are deprecated\n");
632 }
633
634 void Builder::Loader::package(const string &n)
635 {
636         SourcePackage *pkg = new SourcePackage(obj, n, get_source());
637         if(!obj.main_pkg)
638                 obj.main_pkg = pkg;
639
640         if(obj.conf_all || pkg==obj.main_pkg)
641                 load_sub(*pkg, obj.cmdline_options);
642         else
643                 load_sub(*pkg);
644
645         if(obj.build_type)
646                 pkg->set_build_type(*obj.build_type);
647 }