### Home Classes Methods

### In Files

- lib/taskjuggler/daemon/ProjectBroker.rb

### Parent

Daemon

### Methods

- ::new
- #addProject
- #checkKey
- #getProject
- #getProjectList
- #removeProject
- #report
- #start
- #status
- #stop
- #update
- #updateState

### Included Modules

- TaskJuggler::MessageHandler

### Files

- CHANGELOG
- COPYING
- README.rdoc

### Class/Module Index

Quicksearch

- TaskJuggler
- TaskJuggler::Account
- TaskJuggler::AccountAttribute
- TaskJuggler::AccountCredit
- TaskJuggler::AccountCreditListAttribute
- TaskJuggler::AccountListRE
- TaskJuggler::AccountScenario
- TaskJuggler::AlertLevelDefinition
- TaskJuggler::AlertLevelDefinitions
- TaskJuggler::Allocation
- TaskJuggler::AllocationAttribute
- TaskJuggler::AttributeBase
- TaskJuggler::AttributeDefinition
- TaskJuggler::AttributeOverwrite
- TaskJuggler::BatchProcessor
- TaskJuggler::Booking
- TaskJuggler::BookingListAttribute
- TaskJuggler::BooleanAttribute
- TaskJuggler::CSVFile
- TaskJuggler::CellSettingPattern
- TaskJuggler::CellSettingPatternList
- TaskJuggler::Charge
- TaskJuggler::ChargeListAttribute
- TaskJuggler::ChargeSet
- TaskJuggler::ChargeSetListAttribute
- TaskJuggler::ChartPlotter
- TaskJuggler::ChartPlotterError
- TaskJuggler::CollisionDetector
- TaskJuggler::ColumnListAttribute
- TaskJuggler::ColumnTable
- TaskJuggler::Daemon
- TaskJuggler::DaemonConnector
- TaskJuggler::DaemonConnectorMixin
- TaskJuggler::DataCache
- TaskJuggler::DataCacheEntry
- TaskJuggler::DateAttribute
- TaskJuggler::DefinitionListAttribute
- TaskJuggler::DependencyListAttribute
- TaskJuggler::DurationAttribute
- TaskJuggler::ExportRE
- TaskJuggler::FileList
- TaskJuggler::FileRecord
- TaskJuggler::FixnumAttribute
- TaskJuggler::FlagListAttribute
- TaskJuggler::FloatAttribute
- TaskJuggler::FormatListAttribute
- TaskJuggler::GanttChart
- TaskJuggler::GanttContainer
- TaskJuggler::GanttHeader
- TaskJuggler::GanttHeaderScaleItem
- TaskJuggler::GanttLine
- TaskJuggler::GanttLoadStack
- TaskJuggler::GanttMilestone
- TaskJuggler::GanttRouter
- TaskJuggler::GanttTaskBar
- TaskJuggler::HTMLDocument
- TaskJuggler::HTMLElements
- TaskJuggler::HTMLGraphics
- TaskJuggler::ICalReport
- TaskJuggler::ICalendar
- TaskJuggler::ICalendar::Component
- TaskJuggler::ICalendar::Event
- TaskJuggler::ICalendar::Journal
- TaskJuggler::ICalendar::Person
- TaskJuggler::ICalendar::Todo
- TaskJuggler::Interval
- TaskJuggler::IntervalList
- TaskJuggler::JobInfo
- TaskJuggler::Journal
- TaskJuggler::JournalEntry
- TaskJuggler::JournalEntryList
- TaskJuggler::JournalSortListAttribute
- TaskJuggler::KateSyntax
- TaskJuggler::KeywordArray
- TaskJuggler::KeywordDocumentation
- TaskJuggler::Leave
- TaskJuggler::LeaveAllowance
- TaskJuggler::LeaveAllowanceList
- TaskJuggler::LeaveAllowanceListAttribute
- TaskJuggler::LeaveList
- TaskJuggler::LeaveListAttribute
- TaskJuggler::Limits
- TaskJuggler::Limits::Limit
- TaskJuggler::LimitsAttribute
- TaskJuggler::ListAttributeBase
- TaskJuggler::Log
- TaskJuggler::LogicalAttribute
- TaskJuggler::LogicalExpression
- TaskJuggler::LogicalExpressionAttribute
- TaskJuggler::LogicalExpressionListAttribute
- TaskJuggler::LogicalFlag
- TaskJuggler::LogicalFunction
- TaskJuggler::LogicalOperation
- TaskJuggler::ManagerResponsibilities
- TaskJuggler::ManagerStatusRecord
- TaskJuggler::Message
- TaskJuggler::MessageHandler
- TaskJuggler::MessageHandlerInstance
- TaskJuggler::MspXmlRE
- TaskJuggler::Navigator
- TaskJuggler::NavigatorElement
- TaskJuggler::NikuProject
- TaskJuggler::NikuReport
- TaskJuggler::NikuResource
- TaskJuggler::NodeListAttribute
- TaskJuggler::PTNProxy
- TaskJuggler::Painter
- TaskJuggler::Painter::Circle
- TaskJuggler::Painter::Color
- TaskJuggler::Painter::Element
- TaskJuggler::Painter::Ellipse
- TaskJuggler::Painter::FontMetrics
- TaskJuggler::Painter::FontMetricsData
- TaskJuggler::Painter::Group
- TaskJuggler::Painter::Line
- TaskJuggler::Painter::Points
- TaskJuggler::Painter::PolyLine
- TaskJuggler::Painter::Primitives
- TaskJuggler::Painter::Rect
- TaskJuggler::Painter::SVGSupport
- TaskJuggler::Painter::Text
- TaskJuggler::PlaceHolderCell
- TaskJuggler::ProcessIntercom
- TaskJuggler::ProcessIntercomIface
- TaskJuggler::Project
- TaskJuggler::ProjectBroker
- TaskJuggler::ProjectBrokerIface
- TaskJuggler::ProjectFileParser
- TaskJuggler::ProjectFileScanner
- TaskJuggler::ProjectRecord
- TaskJuggler::ProjectServer
- TaskJuggler::ProjectServerIface
- TaskJuggler::PropertyAttribute
- TaskJuggler::PropertyList
- TaskJuggler::PropertySet
- TaskJuggler::PropertyTreeNode
- TaskJuggler::Query
- TaskJuggler::RTFHandlers
- TaskJuggler::RTFNavigator
- TaskJuggler::RTFQuery
- TaskJuggler::RTFReport
- TaskJuggler::RTFReportLink
- TaskJuggler::RTFWithQuerySupport
- TaskJuggler::RealFormat
- TaskJuggler::RealFormatAttribute
- TaskJuggler::ReferenceAttribute
- TaskJuggler::Report
- TaskJuggler::ReportBase
- TaskJuggler::ReportContext
- TaskJuggler::ReportScenario
- TaskJuggler::ReportServer
- TaskJuggler::ReportServerIface
- TaskJuggler::ReportServerRecord
- TaskJuggler::ReportServlet
- TaskJuggler::ReportTable
- TaskJuggler::ReportTableCell
- TaskJuggler::ReportTableColumn
- TaskJuggler::ReportTableLegend
- TaskJuggler::ReportTableLine
- TaskJuggler::Resource
- TaskJuggler::ResourceListAttribute
- TaskJuggler::ResourceListRE
- TaskJuggler::ResourceScenario
- TaskJuggler::RichText
- TaskJuggler::RichTextAttribute
- TaskJuggler::RichTextDocument
- TaskJuggler::RichTextElement
- TaskJuggler::RichTextFunctionExample
- TaskJuggler::RichTextFunctionHandler
- TaskJuggler::RichTextImage
- TaskJuggler::RichTextIntermediate
- TaskJuggler::RichTextParser
- TaskJuggler::RichTextScanner
- TaskJuggler::RichTextSnip
- TaskJuggler::RichTextSyntaxRules
- TaskJuggler::Scenario
- TaskJuggler::ScenarioData
- TaskJuggler::ScenarioListAttribute
- TaskJuggler::Scoreboard
- TaskJuggler::ScoreboardInterval
- TaskJuggler::SheetHandlerBase
- TaskJuggler::SheetReceiver
- TaskJuggler::SheetSender
- TaskJuggler::Shift
- TaskJuggler::ShiftAssignment
- TaskJuggler::ShiftAssignments
- TaskJuggler::ShiftAssignmentsAttribute
- TaskJuggler::ShiftScenario
- TaskJuggler::SimpleQueryExpander
- TaskJuggler::SortListAttribute
- TaskJuggler::StatusSheetReceiver
- TaskJuggler::StatusSheetReport
- TaskJuggler::StatusSheetSender
- TaskJuggler::StdIoWrapper
- TaskJuggler::StringAttribute
- TaskJuggler::SymbolAttribute
- TaskJuggler::SymbolListAttribute
- TaskJuggler::SyntaxReference
- TaskJuggler::TOCEntry
- TaskJuggler::TSResourceRecord
- TaskJuggler::TSTaskRecord
- TaskJuggler::TableColumnDefinition
- TaskJuggler::TableColumnSorter
- TaskJuggler::TableOfContents
- TaskJuggler::TableReport
- TaskJuggler::TableReportColumn
- TaskJuggler::TagFile
- TaskJuggler::TagFile::TagFileEntry
- TaskJuggler::Task
- TaskJuggler::TaskDepListAttribute
- TaskJuggler::TaskDependency
- TaskJuggler::TaskListAttribute
- TaskJuggler::TaskListRE
- TaskJuggler::TaskScenario
- TaskJuggler::TernarySearchTree
- TaskJuggler::TextFormatter
- TaskJuggler::TextParser
- TaskJuggler::TextParser::Macro
- TaskJuggler::TextParser::MacroTable
- TaskJuggler::TextParser::Pattern
- TaskJuggler::TextParser::Rule
- TaskJuggler::TextParser::Scanner
- TaskJuggler::TextParser::Scanner::BufferStreamHandle
- TaskJuggler::TextParser::Scanner::FileStreamHandle
- TaskJuggler::TextParser::Scanner::MacroStackEntry
- TaskJuggler::TextParser::Scanner::StreamHandle
- TaskJuggler::TextParser::SourceFileInfo
- TaskJuggler::TextParser::StackElement
- TaskJuggler::TextParser::State
- TaskJuggler::TextParser::StateTransition
- TaskJuggler::TextParser::TextParserResultArray
- TaskJuggler::TextParser::TokenDoc
- TaskJuggler::TextReport
- TaskJuggler::TimeInterval
- TaskJuggler::TimeIntervalListAttribute
- TaskJuggler::TimeSheet
- TaskJuggler::TimeSheetReceiver
- TaskJuggler::TimeSheetRecord
- TaskJuggler::TimeSheetReport
- TaskJuggler::TimeSheetSender
- TaskJuggler::TimeSheetSummary
- TaskJuggler::TimeSheets
- TaskJuggler::Tj3
- TaskJuggler::Tj3AppBase
- TaskJuggler::Tj3Client
- TaskJuggler::Tj3Daemon
- TaskJuggler::Tj3Man
- TaskJuggler::Tj3SheetAppBase
- TaskJuggler::Tj3SsReceiver
- TaskJuggler::Tj3SsSender
- TaskJuggler::Tj3TsReceiver
- TaskJuggler::Tj3TsSender
- TaskJuggler::Tj3TsSummary
- TaskJuggler::Tj3WebD
- TaskJuggler::TjException
- TaskJuggler::TjRuntimeError
- TaskJuggler::TjTime
- TaskJuggler::TjpExample
- TaskJuggler::TjpExportRE
- TaskJuggler::TjpSyntaxRules
- TaskJuggler::TraceReport
- TaskJuggler::URLParameter
- TaskJuggler::UserManual
- TaskJuggler::VimSyntax
- TaskJuggler::WebServer
- TaskJuggler::WelcomePage
- TaskJuggler::WorkingHours
- TaskJuggler::WorkingHoursAttribute
- TaskJuggler::XMLBlob
- TaskJuggler::XMLComment
- TaskJuggler::XMLDocument
- TaskJuggler::XMLElement
- TaskJuggler::XMLNamedText
- TaskJuggler::XMLText
- Diff
- Diff::Hunk
- AppConfig
- Diffable
- DiffableString
- Object
- RuntimeConfig
- String

No matching classes.

# TaskJuggler::ProjectBroker

The ProjectBroker is the central object of the TaskJuggler daemon. It can manage multiple scheduled projects that it keeps in separate sub processes. Requests to a specific project will be redirected to the specific ProjectServer process. Projects can be added or removed. Adding an already existing one (identified by project ID) will replace the old one as soon as the new one has been scheduled successfully.

The daemon uses DRb to communicate with the client and it's sub processes. The communication is restricted to localhost. All remote commands require an authentication key.

Currently only tj3client can be used to communicate with the TaskJuggler daemon.

### Attributes

authKey[RW]
logStdIO[RW]
port[RW]
projectFiles[RW]
uriFile[RW]

### Public Class Methods

new() click to toggle source

    # File lib/taskjuggler/daemon/ProjectBroker.rb, line 42
    def initialize
      super
      # We don't have a default key. The user must provice a key in the config
      # file. Otherwise the daemon will not start.
      @authKey = nil
      # The default TCP/IP port. ASCII code decimals for 'T' and 'J'.
      @port = 8474
      # The name of the URI file.
      @uriFile = nil
      # A list of loaded projects as Array of ProjectRecord objects.
      @projects = []
      # We operate with multiple threads so we need a Monitor to synchronize
      # the access to the list.
      @projects.extend(MonitorMixin)

      # A list of the initial projects. Array with Array of files names.
      @projectFiles = []

      # This Queue is used to load new projects. The DRb thread pushes load
      # requests that the housekeeping thread will then perform.
      @projectsToLoad = Queue.new

      # Set this flag to true to have standard IO logged into files. There
      # will be seperate set of files for each process.
      @logStdIO = !@daemonize

      # This flag will be set to true to terminate the daemon.
      @terminate = false
    end

### Public Instance Methods

addProject(cwd, args, stdOut, stdErr, stdIn, silent) click to toggle source

Adding a new project or replacing an existing one. The command waits until the project has been loaded or the load has failed.

    # File lib/taskjuggler/daemon/ProjectBroker.rb, line 194
    def addProject(cwd, args, stdOut, stdErr, stdIn, silent)
      # We need some tag to identify the ProjectRecord that this project was
      # associated to. Just use a large enough random number.
      tag = rand(9999999999999)

      debug('', "Pushing #{tag} to load Queue")
      @projectsToLoad.push(tag)

      # Now we have to wait until the project shows up in the @projects
      # list. We use our tag to identify the right entry.
      pr = nil
      while pr.nil?
        @projects.synchronize do
          @projects.each do |p|
            if p.tag == tag
              pr = p
              break
            end
          end
        end
        # The wait in this loop should be pretty short and we don't want to
        # miss IO from the ProjectServer process.
        sleep 0.1 unless pr
      end

      debug('', "Found tag #{tag} in list of loaded projects with URI " +
            "#{pr.uri}")

      res = false

      # Open a DRb connection to the ProjectServer process
      begin
        projectServer = DRbObject.new(nil, pr.uri)
      rescue
        warning('pb_cannot_get_ps', "Can't get ProjectServer object: #{$!}")
        return false
      end
      begin
        # Hook up IO from requestor to the ProjectServer process.
        projectServer.connect(pr.authKey, stdOut, stdErr, stdIn, silent)
      rescue
        warning('pb_cannot_connect_io', "Can't connect IO: #{$!}")
        return false
      end

      # Ask the ProjectServer to load the files in _args_ into the
      # ProjectServer.
      begin
        res = projectServer.loadProject(pr.authKey, [ cwd, *args ])
      rescue
        warning('pb_load_failed', "Loading of project failed: #{$!}")
        return false
      end

      # Disconnect the IO from the ProjectServer and close the DRb connection.
      begin
        projectServer.disconnect(pr.authKey)
      rescue
        warning('pb_cannot_disconnect_io', "Can't disconnect IO: #{$!}")
        return false
      end

      res
    end

checkKey(authKey, command) click to toggle source

All remote commands must provide the proper authentication key. Usually the client and the server get this secret key from the same configuration file.

    # File lib/taskjuggler/daemon/ProjectBroker.rb, line 141
    def checkKey(authKey, command)
      if authKey == @authKey
        debug('', "Accepted authentication key for command '#{command}'")
      else
        warning('wrong_auth_key',
                "Rejected wrong authentication key '#{authKey}' " +
                "for command '#{command}'")
        return false
      end
      true
    end

getProject(projectId) click to toggle source

Return the ProjectServer URI and authKey for the project with project ID projectId.

    # File lib/taskjuggler/daemon/ProjectBroker.rb, line 289
    def getProject(projectId)
      # Find the project with the ID args[0].
      project = nil
      @projects.synchronize do
        @projects.each do |p|
          project = p if p.id == projectId && p.state == :ready
        end
      end

      if project.nil?
        debug('', "No project with ID #{projectId} found")
        return [ nil, nil ]
      end
      [ project.uri, project.authKey ]
    end

getProjectList() click to toggle source

Return a list of IDs of projects that are in state :ready.

    # File lib/taskjuggler/daemon/ProjectBroker.rb, line 319
    def getProjectList
      list = []
      @projects.synchronize do
        @projects.each do |project|
          list << project.id if project.state == :ready
        end
      end
      list
    end

removeProject(indexOrId) click to toggle source

    # File lib/taskjuggler/daemon/ProjectBroker.rb, line 259
    def removeProject(indexOrId)
      @projects.synchronize do
        # Find all projects with the IDs in indexOrId and mark them as
        # :obsolete.
        if /^[0-9]$/.match(indexOrId)
          index = indexOrId.to_i - 1
          if index >= 0 && index < @projects.length
            # If we have marked the project as obsolete, we return false to
            # indicate the double remove.
            return false if p.state == :obsolete
            @projects[index].state = :obsolete
            return true
          end
        else
          @projects.each do |p|
            if indexOrId == p.id
              # If we have marked the project as obsolete, we return false to
              # indicate the double remove.
              return false if p.state == :obsolete
              p.state = :obsolete
              return true
            end
          end
        end
      end
      false
    end

report(projectId, reportId) click to toggle source

    # File lib/taskjuggler/daemon/ProjectBroker.rb, line 329
    def report(projectId, reportId)
      uri, key = getProject(projectId)
    end

start() click to toggle source

    # File lib/taskjuggler/daemon/ProjectBroker.rb, line 72
    def start
      # To ensure a certain level of security, the user must provide an
      # authentication key to authenticate the client to this server.
      unless @authKey
        error('pb_no_auth_key', You must set an authentication key in the configuration file. Create a filenamed .taskjugglerrc or taskjuggler.rc that contains at least the followinglines. Replace 'your_secret_key' with some random character sequence._global:  authKey: your_secret_key
                  )
      end

      # In daemon mode, we fork twice and only the 2nd child continues here.
      super()
      debug('', "Starting project broker")

      # Setup a DRb server to handle the incomming requests from the clients.
      brokerIface = ProjectBrokerIface.new(self)
      begin
        $SAFE = 1
        DRb.install_acl(ACL.new(] deny all
                                    allow 127.0.0.1 ]))
        @uri = DRb.start_service("druby://127.0.0.1:#{@port}", brokerIface).uri
        info('daemon_uri', "TaskJuggler daemon is listening on #{@uri}")
      rescue
        error('port_in_use', "Cannot listen on port #{@port}: #{$!}")
      end

      if @port == 0 && @uriFile
        # If the port is set to 0 (any port) we save the ProjectBroker URI in
        # the file .tj3d.uri. tj3client will look for it.
        begin
          File.open(@uriFile, 'w') { |f| f.write @uri }
        rescue
          error('cannot_write_uri', "Cannot write URI file #{@uriFile}: #{$!}")
        end
      end

      # If project files were specified on the command line, we add them here.
      i = 0
      @projectFiles.each do |project|
        @projectsToLoad.push(project)
      end

      # Start a Thread that waits for the @terminate flag to be set and does
      # some other work asynchronously.
      startHousekeeping

      debug('', 'Shutting down ProjectBroker DRb server')
      DRb.stop_service

      # If we have created a URI file, we need to delete it again.
      if @port == 0 && @uriFile
        begin
          File.delete(@uriFile)
        rescue
          error('cannot_delete_uri', "Cannot delete URI file .tj3d.uri: #{$!}")
        end
      end

      info('daemon_terminated', 'TaskJuggler daemon terminated')
    end

status() click to toggle source

Generate a table with information about the loaded projects.

    # File lib/taskjuggler/daemon/ProjectBroker.rb, line 174
    def status
      if @projects.empty?
        "No projects registered\n"
      else
        format = "  %3s | %-25s | %-14s | %s | %-20s\n"
        out = sprintf(format, 'No.', 'Project ID', 'Status', 'M',
                              'Loaded since')
        out += "  #{'-' * 4}+#{'-' * 27}+#{'-' * 16}+#{'-' * 3}+#{'-' * 20}\n"
        @projects.synchronize do
          i = 0
          @projects.each do |project|
            out += project.to_s(format, i += 1)
          end
        end
        out
      end
    end

stop() click to toggle source

This command will initiate the termination of the daemon.

    # File lib/taskjuggler/daemon/ProjectBroker.rb, line 154
    def stop
      debug('', 'Terminating on client request')

      # Shut down the web server if we've started one.
      if @webServer
        @webServer.stop
      end

      # Send termination signal to all ProjectServer instances
      @projects.synchronize do
        @projects.each { |p| p.terminateServer }
      end

      # Setting the @terminate flag to true will case the terminator Thread to
      # call DRb.stop_service
      @terminate = true
      super
    end

update() click to toggle source

Reload all projects that have modified files and are not already being reloaded.

    # File lib/taskjuggler/daemon/ProjectBroker.rb, line 307
    def update
      @projects.synchronize do
        @projects.each do |project|
          if project.modified && !project.reloading
            project.reloading = true
            @projectsToLoad.push(project.files)
          end
        end
      end
    end

updateState(projectKey, filesOrId, state, modified) click to toggle source

This is a callback from the ProjectServer process. It's used to update the current state of the ProjectServer in the ProjectRecord list. projectKey is the authentication key for that project. It is used to idenfity the entry in the ProjectRecord list to be updated.

    # File lib/taskjuggler/daemon/ProjectBroker.rb, line 337
    def updateState(projectKey, filesOrId, state, modified)
      result = false
      if filesOrId.is_a?(Array)
        files = filesOrId
        # Use the name of the master files for now.
        id = files[1]
      elsif filesOrId.is_a?(String)
        id = filesOrId
        files = nil
      else
        id = files = nil
      end

      @projects.synchronize do
        @projects.each do |project|
          # Don't accept updates for already obsolete entries.
          next if project.state == :obsolete

          debug('', "Updating state for #{id} to #{state}")
          # Only update the record that has the matching key
          if project.authKey == projectKey
            project.id = id if id
            # An Array of [ workingDir, tjpFile, ... other tji files ]
            project.files = files if files

            # If the state is being changed from something to :ready, this is
            # now the current project for the project ID.
            if state == :ready && project.state != :ready
              # Mark other project records with same project ID as obsolete
              @projects.each do |p|
                if p != project && p.id == id
                  p.state = :obsolete
                  debug('', "Marking entry with ID #{id} as obsolete")
                end
              end
              project.readySince = TjTime.new
            end

            # Failed ProjectServers are terminated automatically. We can't
            # reach them any more.
            project.uri = nil if state == :failed

            project.state = state
            project.modified = modified
            result = true
            break
          end
        end
      end

      result
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.