Class: RallyVCSConnection

Inherits:
VCSConnection show all
Defined in:
lib/vcseif/rally_vcs_connection.rb

Constant Summary collapse

RALLY_VCS_CONNECTION_VERSION =
"1.2.0"
WSAPI_VERSION =
"1.43"
VALID_ARTIFACT_TYPES =
['HierarchicalRequirement', 'Task', 'Defect', 'DefectSuite']
ISO8601_TS_FORMAT =
"%Y-%m-%dT%H:%M:%SZ"
EXTENSION_SPEC_PATTERN =
Regexp.compile('^(?<ext_class>[\w\.]+)\s*\((?<ext_parm>[^\)]+)\)$')

Constants inherited from VCSConnection

VCSConnection::REVFILE_TOKEN, VCSConnection::REVNUM_TOKEN

Instance Attribute Summary collapse

Attributes inherited from VCSConnection

#changeset_selectors, #config, #connected, #file_uri, #log, #password, #password_required, #rev_uri, #sshkey_path, #username, #username_required

Instance Method Summary collapse

Methods inherited from VCSConnection

#get_file_rev_uri, #get_rev_uri, #is_windows?

Constructor Details

#initialize(config, logger) ⇒ RallyVCSConnection

Returns a new instance of RallyVCSConnection.



48
49
50
51
52
53
54
55
56
57
58
# File 'lib/vcseif/rally_vcs_connection.rb', line 48

def initialize(config, logger)
    @valid_artifact_pattern = nil # set after config with artifact prefixes are known
    super(logger)
    internalizeConfig(config) 
    @log.info("Rally WSAPI Version %s" % rallyWSAPIVersion)
    @integration_other_version = ""
    @username_required = true
    @password_required = true
    @operational_errors = 0
    @user_cache = {}
end

Instance Attribute Details

#extensionsObject (readonly)

Returns the value of attribute extensions.



44
45
46
# File 'lib/vcseif/rally_vcs_connection.rb', line 44

def extensions
  @extensions
end

#operational_errorsObject

Returns the value of attribute operational_errors.



43
44
45
# File 'lib/vcseif/rally_vcs_connection.rb', line 43

def operational_errors
  @operational_errors
end

#rallyObject

Returns the value of attribute rally.



43
44
45
# File 'lib/vcseif/rally_vcs_connection.rb', line 43

def rally
  @rally
end

#rally_wsapi_versionObject (readonly)

Returns the value of attribute rally_wsapi_version.



45
46
47
# File 'lib/vcseif/rally_vcs_connection.rb', line 45

def rally_wsapi_version
  @rally_wsapi_version
end

#repo_refObject (readonly)

Returns the value of attribute repo_ref.



45
46
47
# File 'lib/vcseif/rally_vcs_connection.rb', line 45

def repo_ref
  @repo_ref
end

#serverObject

Returns the value of attribute server.



42
43
44
# File 'lib/vcseif/rally_vcs_connection.rb', line 42

def server
  @server
end

#user_cacheObject (readonly)

Returns the value of attribute user_cache.



46
47
48
# File 'lib/vcseif/rally_vcs_connection.rb', line 46

def user_cache
  @user_cache
end

#valid_artifact_patternObject (readonly)

Returns the value of attribute valid_artifact_pattern.



41
42
43
# File 'lib/vcseif/rally_vcs_connection.rb', line 41

def valid_artifact_pattern
  @valid_artifact_pattern
end

Instance Method Details

#changesetExists?(revision_ident) ⇒ Boolean

Returns:

  • (Boolean)


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
# File 'lib/vcseif/rally_vcs_connection.rb', line 709

def changesetExists?(revision_ident)
    """
        Issue a query against Changeset to obtain the Changeset identified by revision_ident.
        Return a boolean indication of whether such an item exists in repository_name.
    """
    criterion1 = 'SCMRepository.Name = "%s"' % @repository_name
    criterion2 = 'Revision = %s'             % revision_ident
    criteria   = '((%s) AND (%s))' % [criterion1, criterion2]
    
    query = RallyAPI::RallyQuery.new({:type   => :changeset, 
                                      :fetch  => "Revision,CommitTimestamp,SCMRepository,Name",
                                      :workspace => @workspace
                                     })
    query.query_string = criteria
    begin
        result = @rally.find(query)
    rescue => ex
        @log.debug(ex.message)
        problem = "Unable to complete Rally query regarding existence of Changeset '%s'" % revision_ident
        operr = VCSEIF_Exceptions::OperationalError.new(problem)
        @operational_errors += 1
        raise operr, problem
    end
    exists = false
    exists = true if not result.nil? and result.total_result_count > 0
    return exists
end

#connectObject



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
# File 'lib/vcseif/rally_vcs_connection.rb', line 283

def connect()
    @log.info("Connecting to Rally")
    custom_headers = get_custom_headers()
    rally_config = { :base_url  => "https://%s/slm" % @config['Server'],
                     :username  => @config['Username' ],
                     :password  => @config['Password' ],
                     :version   => @rally_wsapi_version,
                     :headers   => custom_headers
                   }
    # specifically exclude workspace from rally_config, so we can do a vanilla connect
    # and then see if the workspace value in the @config actually exists
    # in the workspaces available for the user

    proxy = ENV['http_proxy'] || nil
    if not proxy.nil? and not proxy.empty?
        @log.info("Proxy for connection to Rally: %s" % proxy)
        rally_config[:proxy => proxy]
    end

    begin
      @rally = RallyAPI::RallyRestJson.new(rally_config)
      info = @rally.user
    rescue Exception => ex
        @log.debug(ex.message)
        problem = "Unable to connect to Rally at %s as user %s" % [@config['Server'], @config['Username']]
        operr = VCSEIF_Exceptions::OperationalError.new(problem)
        @operational_errors += 1
        raise operr, problem
    end
    @log.info("Connected to Rally server: %s" % @config['Server'])    

    # verify the given workspace name exists
    wksp = @rally.find_workspace(@config['Workspace'])
    if wksp.nil? or (not wksp.nil? and wksp['Name'] != @config['Workspace'])
        desc =  "Specified Workspace: '%s' not in list of workspaces available "
        desc << "for your credentials as user: %s"
        problem = desc % [@config['Workspace'], @config['Username']]
        confex = VCSEIF_Exceptions::ConfigurationError.new(problem)
        raise confex, problem
    end

    # now that we know @config['Workspace'] is a valid workspace, 
    # ensure that all further interactions with Rally are confined to that workspace
    # as embodied in the wksp object we just got back from the check
    @rally.rally_default_workspace = wksp
    @log.info("    Workspace: %s" % @config['Workspace'])
    # and verify that the BuildandChangesetEnabled flag is set for this workspace
    wksp.read()
    wksp_conf = wksp.WorkspaceConfiguration
    wksp_conf.read()
    if wksp_conf.BuildandChangesetEnabled != true
        problem = "The BuildandChangesetEnabled flag is not enabled for the '%s' workspace. " % @config['Workspace']
        problem << "Contact your Rally workspace administrator to set this up."
        confex = VCSEIF_Exceptions::ConfigurationError.new(problem)
        raise confex, problem
    end
    @wksp = wksp
    @workspace_ref = @wksp['_ref']
    @workspace_oid = @workspace_ref.split('/')[-1][0...-3]  # last part of url sans the '.js' suffix
    getArtifactPrefixes()
    @connected = true
    return true
end

#createChangeset(int_work_item) ⇒ Object



524
525
526
527
528
529
530
531
532
533
# File 'lib/vcseif/rally_vcs_connection.rb', line 524

def createChangeset(int_work_item)
    """
        This method should never be overridden (it might be called 'final' in another language).  
        Instead override any of the next three methods.
    """
    modified_int_work_item = preCreate(int_work_item)
    work_item              = _createInternal(modified_int_work_item)
    modified_artifact      = postCreate(work_item)
    return modified_artifact
end

#disconnectObject



404
405
406
407
408
409
410
# File 'lib/vcseif/rally_vcs_connection.rb', line 404

def disconnect()
    """
        Reset our rally instance variable to nil and toggle @connected indicator
    """
    @rally = nil
    @connected = false
end

#extractArtifactFormattedIDs(message) ⇒ Object



904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
# File 'lib/vcseif/rally_vcs_connection.rb', line 904

def extractArtifactFormattedIDs(message)
    %{
        A brute force method to extract what look to be Rally Artifact FormattedID values
        from within the message.  
        The algorithm is to replace any comma chars with a single space, any 
        colon with a single space, any semi-colon with a single space, 
        any '.' char with a single space, any '-' char with a single space  and 
        then split the message on whitespace, resulting in a list of "word" tokens.
        The token list is then subjected to conformance with a pattern for FormattedID 
        fof the types of artifacts that are listed in the configuration.
        Returns the qualified list of tokens that are indeed validly constructed Rally FormattedIDs 
         (although this method makes no attempt to determine that an artifact actually exists for 
          each FormattedID candidate).
     }
    washed_message = message.gsub(',', ' ').gsub(':', ' ').gsub(';', ' ').gsub('.', ' ').gsub('-', ' ')
    message_words = washed_message.split()
    artifact_ids = message_words.select {|token| @valid_artifact_pattern.match(token)}
    @log.debug("candidate FormattedIDs: %s" % artifact_ids.join(", "))
    return artifact_ids.sort
end

#get_custom_headersObject



144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/vcseif/rally_vcs_connection.rb', line 144

def get_custom_headers()
    custom_headers =  RallyAPI::CustomHttpHeader.new()
    custom_headers.name    = @integration_name    || "Rally VCS Connector for UNKNOWN"
    custom_headers.vendor  = @integration_vendor  || 'Rally'
    custom_headers.version = @integration_version || "1.0"
    
    if not @integration_other_version.empty?
        conn_ver_target_ver = "%s - %s" % [custom_headers.version, @integration_other_version]
        custom_headers.version = conn_ver_target_ver
    end
    return custom_headers
end

#getArtifactPrefixesObject



347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/vcseif/rally_vcs_connection.rb', line 347

def getArtifactPrefixes()
    @artifact_type   = {}
    @artifact_prefix = {}
    @art_prefixes = []

    query_info = { :type => :typedefinition, :fetch => "ElementName,IDPrefix", 
                   :workspace => @wksp } 
    pfx_query = RallyAPI::RallyQuery.new(query_info)
    results = @rally.find(pfx_query)
    for typedef in results do
        next if typedef['IDPrefix'].nil? or typedef['IDPrefix'].empty?
        next if not VALID_ARTIFACT_TYPES.include?(typedef['ElementName'])
        art_type = typedef['ElementName']
        art_type = 'UserStory' if art_type == 'HierarchicalRequirement'
        art_prefix = typedef['IDPrefix']
        @artifact_type[art_prefix] = art_type
        @artifact_prefix[art_type] = art_prefix
        @art_prefixes << art_prefix
    end
    prefixes = @artifact_prefix.values.join('|')
    @valid_artifact_pattern = Regexp.compile('^(%s)\d+$' % prefixes)
end

#getArtifacts(targets) ⇒ Object



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
# File 'lib/vcseif/rally_vcs_connection.rb', line 738

def getArtifacts(targets)
    """
        For now this is brute force requiring a thump on the Rally endpoint for each artifact FormattedID.
        TODO: consider caching for quicker turnaround and killing the duplicative queries.
    """
    artifacts = []
    targets.each do |target|
        prefix = target.gsub(/\d/, '')
        rally_entity_type = @artifact_type[prefix].downcase.to_sym
        query = RallyAPI::RallyQuery.new(:type  => rally_entity_type,
                                         :fetch => "ObjectID,Name,FormattedID,ScheduleState,State",
                                         :workspace => @wksp)
        query.query_string = '(FormattedID = %s)' % target
        begin
            results = @rally.find(query)
        rescue Exception => ex
            # TODO: determine if setting missing to the text here is accurate,
            #       we should only hit this if the Rally WSAPI call fails,
            #       if there is no such Artifact, the query should return with empty results
            missing = "No such Artifact: '%s' found in Rally for workspace: %s"
            @log.warning(missing % [target, @workspace_name])
        end
        if !results.nil? and results.total_result_count > 0
            artifact = results.first
            @log.debug("artifact obtained: %s" % artifact.FormattedID)
            artifacts << artifact
        end
        
    end
    return artifacts
end

#getBackendVersionObject



72
73
74
75
76
77
78
# File 'lib/vcseif/rally_vcs_connection.rb', line 72

def getBackendVersion()
    %{
        Conform to Connection subclass protocol which requires the version of 
        the system this instance is "connected" to.
     }
    return "Rally WSAPI %s" % rallyWSAPIVersion
end

#getRallyUsers(attributes = nil) ⇒ Object



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
# File 'lib/vcseif/rally_vcs_connection.rb', line 770

def getRallyUsers(attributes=nil)
    """
        Run a REST get against Rally using @rally to get User information for all Rally
        users in the currently scoped workspace and populate a cache keyed by the transform
        lookup target with the UserName as the value for each key.
        This makes it a snap to service the lookup method, we just have to consult the cache.
    """
    fetch_fields = "_ref,UserName"
    attributes.gsub(/UserName,?/, '') if !attributes.nil? and attributes =~ /UserName/
    fetch_fields += "," + attributes  if !attributes.nil? and !attributes.empty?
    fetch_fields += ",DisplayName"    if fetch_fields !~ /DisplayName/
    query = RallyAPI::RallyQuery.new(:type => :user, :fetch => fetch_fields)
    begin 
        results = @rally.find(query)
    rescue Exception => ex
        if @log and @log.respond_to?('error')
            @log.error("Unable to retrieve User information from Rally")
        end
        raise
    end
   
    results.each do |user|
        urec = {}
        urec["ref"] = user.send("_ref")
        if not attributes.nil?
            for attr_name in attributes.split(',') do
                urec[attr_name] = user.send(attr_name)
            end
        end
        urec['UserName']    = user.send('UserName')    if not urec.has_key?('UserName')
        urec['DisplayName'] = user.send('DisplayName') if not urec.has_key?('DisplayName')
        @user_cache[urec['UserName']] = urec
        if @log and @log.respond_to?('debug')
            @log.debug("user cache item |%s|" % urec['UserName'])
        end
    end
    return @user_cache.dup  # let caller have their own copy of the @user_cache
end

#getRecentChangesets(ref_time) ⇒ Object



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
# File 'lib/vcseif/rally_vcs_connection.rb', line 470

def getRecentChangesets(ref_time)
    """
        Obtain all Changesets created in Rally at or after the ref_time parameter
        (which is a Time instance)
    """
    ref_time_readable = ref_time.to_s.sub('UTC', 'Z')
    ref_time_iso      = ref_time.iso8601
    @log.info("Detecting recently added Rally Changesets")
    selectors = ['SCMRepository.Name = "%s"' % @repository_name,
                 'CreationDate >= %s'        % ref_time_iso
                ]
    # TODO: See if having ChangesetSelectors is something that will be useful,
    #       but note that it will necessitate "binary'ing" the resultant query conditions
    #       to the Rally WSAPI requirements.
    #for cs in changeset_selectors do
    #    sel = '%s %s "%s"' % [cs.field, ss.relation, cs.value]
    #    selectors << sel
    #end

    log_msg = '   recent Changesets query: %s' % selectors.join(' AND ')
    @log.info(log_msg)

    chgset_query = RallyAPI::RallyQuery.new(:type      => :changeset,
                                            :fetch     => "Revision,CommitTimestamp",
                                            :workspace => @workspace,
                                            :project   => nil,
                                            :pagesize  =>  200,
                                            :limit     => 2000)
    chgset_query.query_string = '((%s) AND (%s))' % selectors  # P-eeee-yuuuhhhh (syntax)!

    begin
        results = @rally.find(chgset_query)
    rescue => ex
        bomex = VCSEIF_Exceptions::UnrecoverableException.new(ex.message)
        raise boomex, ex.message.to_s
    end

    log_msg = "  %d recently added Rally Changesets detected"
    @log.info(log_msg % results.total_result_count)
    changesets = []
    results.each do |changeset|
        changeset['ident'] = changeset.Revision
        changesets << changeset
    end

    if not changesets.empty?
      last_changeset = changesets.last  
      @log.info("date of last reflected Changeset in Rally: #{last_changeset.CommitTimestamp}")
    end

    return changesets
end

#internalizeConfig(config) ⇒ Object



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
# File 'lib/vcseif/rally_vcs_connection.rb', line 80

def internalizeConfig(config)
    super(config)

    @server = false
    @server = config['Server'] if config.has_key?('Server')
    if !@server || @server.nil?
        problem = "RallyConnection spec missing a value for Server"
        confex = VCSEIF_Exceptions::ConfigurationError.new(problem)
        raise confex, problem
    end
    if server.downcase =~ /http:/ or server.downcase =~ /\/slm/
        @log.error("Rally URL should be in the form 'rally1.rallydev.com'")
        problem = "RallyConnection Server spec invalid format"
        confex = VCSEIF_Exceptions::ConfigurationError.new(problem)
        raise confex, problem
    end

    proxy = config['Proxy'] || nil
    set_proxy_info(config) if not proxy.nil?

    @rally_wsapi_version = config['WSAPIVersion'] || WSAPI_VERSION
    @workspace_name    = config['Workspace']      || nil
    @repository_name   = config['RepositoryName'] || nil
    @repo_ref = nil
    @restapi_debug     = config['Debug'] || false
    @restapi_logger    = @log
    #@restapi_logger   = @log if restapi_debug || nil
end

#nameObject



60
61
62
# File 'lib/vcseif/rally_vcs_connection.rb', line 60

def name()
    "Rally"
end

#rallyWSAPIVersionObject



68
69
70
# File 'lib/vcseif/rally_vcs_connection.rb', line 68

def rallyWSAPIVersion()
    @rally_wsapi_version
end

#set_integration_header(header_info) ⇒ Object



158
159
160
161
162
163
164
165
# File 'lib/vcseif/rally_vcs_connection.rb', line 158

def set_integration_header(header_info)
    @integration_name    = header_info['name']
    @integration_vendor  = header_info['vendor']
    @integration_version = header_info['version']
    if header_info.has_key?('other_version')
        @integration_other_version = header_info['other_version']
    end
end

#set_proxy_info(config) ⇒ Object



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
# File 'lib/vcseif/rally_vcs_connection.rb', line 110

def set_proxy_info(config)
    """
        Given the config with any Proxy* related items, the simple case is to assemble the
        final proxy to be stuffed in ENV['http_proxy'] as <protocol>://<proxy>.
        If the config has config['ProxyUser'] and config['ProxyPassword'] values, then
        the final proxy is assembled with <protocol>://<proxy_credentials>@<proxy>
        and stuffed in ENV['http_proxy'].
    """
    proxy = config['Proxy']
    proxy_protocol = config['ProxyProtocol'] || "http"  # protocol default is 'http'
    if proxy.downcase =~ /^(https?):\/\/(.+)$/
        proxy_protocol = $1
        proxy          = $2
    end

    proxy_user     = config['ProxyUser']     || nil
    proxy_password = config['ProxyPassword'] || nil

    if proxy_user.nil? and proxy_password.nil?
        proxy = "%s://%s" % [proxy_protocol, proxy]
    elsif not proxy_user.nil? and not proxy_password.nil?
        proxy_credentials = "%s:%s" % [proxy_user, proxy_password]
        proxy = "%s://%s@%s" % [proxy_protocol, proxy_credentials, proxy]
    else # one of proxy_user / proxy_password is nil
        problem = "Proxy specified, insufficient proxy authentication information supplied"
        @log.error(problem)
        problem = "RallyConnection ProxyUser/ProxyPassword settings must both have values"
        confex = VCSEIF_Exceptions::ConfigurationError.new(problem)
        raise confex, problem
    end
    ENV['http_proxy'] = proxy
end

#setSourceIdentification(vcs_type, vcs_uri) ⇒ Object



168
169
170
171
# File 'lib/vcseif/rally_vcs_connection.rb', line 168

def setSourceIdentification(vcs_type, vcs_uri)
    @vcs_type = vcs_type
    @vcs_uri  = vcs_uri
end

#validateObject



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
# File 'lib/vcseif/rally_vcs_connection.rb', line 370

def validate()
    # obtain a ref to the target SCMRepository
    @log.info("SCMRepository: %s" % @config['RepositoryName'])
    repo_name = @config['RepositoryName']
    #todo should this get defaulted by the connector?  it doesn't at the moment
    if repo_name.nil?
        problem = "A repo name must be specified in the Rally section of the config."
        @log.error(problem)
        confex = VCSEIF_Exceptions::ConfigurationError.new(problem)
        raise confex, problem
    end

    repo = getSCMRepository(@wksp, repo_name)

    if repo.nil?
        repo = createSCMRepository(repo_name, @vcs_type, 'Created by VCSConnector', @vcs_uri)
        action = "created SCMRepository: '%s' in the '%s' workspace"
        @log.info(action % [repo_name, @workspace_name])
    else
        repo.read()
        repo_oid = repo['_ref'].split('/')[-1][0...-3]
        created = Time.parse(repo['CreationDate'])
        found_repo = "Found SCMRepository '%s' with OID of %s created on %s in workspace '%s'"
        @log.debug(found_repo % [repo_name, repo_oid, created.localtime, @wksp['Name']])
    end
    repo_oid = repo['_ref'].split('/')[-1][0...-3]
    @repo_ref = 'scmrepository/%s' % repo_oid

    configureExtensionEnvironment()

  return true
end

#versionObject



64
65
66
# File 'lib/vcseif/rally_vcs_connection.rb', line 64

def version()
    RALLY_VCS_CONNECTION_VERSION
end