Best Selenium code snippet using Platform.ci
application_controller.rb
Source:application_controller.rb
...21 class UnauthorizedException < Exception22 end23 rescue_from(Exception, :with => :handle_generic_exception)24 rescue_from(UnauthorizedException, :with => :handle_unauthorized)25 rescue_from(Cms::Ci::NotFoundException, :with => :handle_ci_not_found)26 helper_method :in_catalog?, :in_design?, :in_transition?, :in_operations?,27 :is_admin?, :manages_access?, :manages_access_for_cloud?, :manages_access_for_assembly?,28 :has_org_scope?, :dto_allowed?, :locate_assemblies,29 :has_design?, :has_transition?, :has_operations?,30 :has_cloud_services?, :has_cloud_compliance?, :has_cloud_support?, :allowed_to_settle_approval?,31 :path_to_ci, :path_to_ci!, :path_to_ns, :path_to_ns!, :path_to_release, :path_to_deployment,32 :ci_image_url, :ci_class_image_url, :platform_image_url, :pack_image_url,33 :graphvis_sub_ci_remote_images, :packs_info, :pack_versions, :design_platform_ns_path,34 :has_support_permission?35 AR_CLASSES_WITH_HEADERS = [Cms::Ci, Cms::DjCi, Cms::Relation, Cms::DjRelation, Cms::RfcCi, Cms::RfcRelation,36 Cms::Release, Cms::ReleaseBom, Cms::Procedure, Transistor,37 Cms::Deployment, Cms::DeploymentCi, Cms::DeploymentRecord,38 Cms::DeploymentRelation, Cms::DeploymentApproval]39 def in_catalog?40 self.class.name.include?('Catalog')41 end42 def in_design?43 self.class.name.include?('Design')44 end45 def in_transition?46 self.class.name.include?('Transition')47 end48 def in_operations?49 self.class.name.include?('Operations')50 end51 def cors_options52 render :nothing => true, :status => :ok53 end54 def search55 @source = params[:source].presence || (request.format.json? ? 'cms' : 'es')56 return if request.format == 'text/html'57 min_ns_path = search_ns_path58 ns_path = params[:ns_path] || min_ns_path59 unless ns_path.start_with?(min_ns_path)60 unauthorized('Invalid namespace')61 return62 end63 class_name = params[:class_name]64 rel_name = params[:relation_name]65 attr_name = params[:attr_name]66 attr_value = params[:attr_value]67 @search_results = []68 if @source == 'cms' || @source == 'simple'69 # CMS search.70 query_params = {:nsPath => ns_path, :recursive => true}71 query_params[:ciClassName] = class_name if class_name.present?72 query_params[rel_name.include?('.') ? :relationName : :relationShortName] = rel_name if rel_name.present?73 if attr_name.present? && attr_value.present?74 attr_operator = params[:attr_operator] || 'eq'75 attr_value = "%#{attr_value}%" if attr_operator == 'like'76 query_params[:attr] = "#{attr_name}:#{attr_operator}:#{attr_value}"77 end78 if rel_name.present?79 query_params[:includeFromCi] = true unless params[:include_from_ci] == 'false'80 query_params[:includeToCi] = true unless params[:include_to_ci] == 'false'81 class_name = params[:from_class_name]82 query_params[:fromClassName] = class_name if class_name.present?83 class_name = params[:to_class_name]84 query_params[:targetClassName] = class_name if class_name.present?85 clazz = Cms::Relation86 else87 clazz = Cms::Ci88 end89 @search_results = clazz.all(:params => query_params) if query_params.size > 290 else91 # ES search.92 query = params[:query].presence93 max_size = (params[:max_size].presence || 1000).to_i94 if query.present? || class_name.present?95 begin96 search_params = {:nsPath => "#{ns_path}#{'/' unless ns_path.last == '/'}*", :size => max_size}97 search_params[:query] = {:query => query, :fields => %w(ciAttributes.* ciClassName ciName)} if query.present?98 # search_params[:query] = query if query.present?99 search_params['ciClassName.keyword'] = class_name if class_name.present?100 @search_results = Cms::Ci.search(search_params)101 rescue Exception => e102 @error = e.message103 end104 end105 end106 unless @search_results || is_admin? || has_org_scope?107 org_ns_path = organization_ns_path108 prefixes = current_user.organization.ci_proxies.where(:ns_path => org_ns_path).joins(:teams).where('teams.id IN (?)', current_user.all_team_ids).pluck(:ci_name).inject([]) do |a, ci_name|109 a << "#{org_ns_path}/#{ci_name}"110 end111 if prefixes.present?112 reg_exp = /^(#{prefixes.join(')|(')})/113 @search_results = @search_results.select {|r| r.nsPath =~ reg_exp}114 else115 @search_results = []116 end117 end118 if @search_results.present? && attr_name.present? && attr_value.blank?119 split = attr_name.split('.')120 split = split.unshift(rel_name.present? ? 'relationAttributes' : 'ciAttributes') if split.size == 1121 @search_results = @search_results.map do |r|122 split.inject(r) do |r, name|123 rr = r.try(name.to_sym)124 break r unless r125 rr126 end127 end128 end129 respond_to do |format|130 format.js { render 'base/search/search' }131 format.json do132 if @error133 render :json => {:errors => [@error]}, :status => :unprocessable_entity134 else135 render :json => @search_results136 end137 end138 format.text do139 if @error140 render :text => @error, :status => :unprocessable_entity141 else142 render :text => @search_results.join(params[:delimeter] || ' ')143 end144 end145 end146 end147 protected148 def ci_resource149 # Should be overwritten by subclasses.150 raise Exception.new("Controller #{self.class.name} did not define target resource.")151 end152 def locate_proxy(qualifier, ns_path)153 find_params = {'ci_proxies.ns_path' => ns_path}154 if qualifier =~ /\D/155 # Must be a ciName, look it up by ciName and namespace.156 find_params['ci_proxies.ci_name'] = qualifier157 else158 # All digits, must be a ciId, look it up by ID.159 find_params['ci_proxies.ci_id'] = qualifier160 end161 current_user.organization.ci_proxies.where(find_params).first162 end163 def find_or_create_proxy(ci)164 current_user.organization.ci_proxies.find_or_create_by(:organization_id => current_user.organization_id,165 :ci_id => ci.ciId,166 :ci_name => ci.ciName,167 :ns_path => ci.nsPath,168 :ci_class_name => ci.ciClassName)169 end170 def search_ns_path171 organization_ns_path172 end173 def custom_log_info174 @exception && {:exception => @exception.to_s, :backtrace => @exception.respond_to?(:backtrace) && @exception.backtrace}175 end176 helper_method :organization_ns_path,177 :assembly_ns_path,178 :environment_ns_path,179 :environment_manifest_ns_path,180 :environment_bom_ns_path,181 :search_ns_path182 def organization_ns_path(org = current_user.organization.name)183 "/#{org}"184 end185 def services_ns_path186 "#{organization_ns_path}/_services"187 end188 def clouds_ns_path(org = current_user.organization.name)189 "#{organization_ns_path(org)}/_clouds"190 end191 def cloud_ns_path(cloud)192 "#{organization_ns_path}/_clouds/#{cloud.ciName}"193 end194 def cloud_zone_ns_path(zone)195 "#{zone.nsPath}/#{zone.ciName}"196 end197 def cloud_service_ns_path(service)198 "#{service.nsPath}/#{service.ciClassName}/#{service.ciName}"199 end200 def private_catalog_designs_ns_path201 "#{organization_ns_path}/_catalogs"202 end203 def catalog_designs_ns_path204 '/public/packer/catalogs'205 end206 def catalog_design_ns_path(design_ci)207 "#{design_ci.nsPath}/#{design_ci.ciName}"208 end209 def catalog_design_platform_ns_path(design_ci, platform_ci)210 "#{catalog_design_ns_path(design_ci)}/_design/#{platform_ci.ciName}"211 end212 def assembly_ns_path(assembly_ci)213 "#{organization_ns_path}/#{assembly_ci.ciName}"214 end215 def design_ns_path(assmebly_ci)216 "#{organization_ns_path}/#{assmebly_ci.ciName}/_design"217 end218 def environment_ns_path(environment_ci)219 "#{environment_ci.nsPath}/#{environment_ci.ciName}"220 end221 def environment_manifest_ns_path(environment_ci)222 "#{environment_ns_path(environment_ci)}/manifest"223 end224 def environment_bom_ns_path(environment_ci)225 "#{environment_ns_path(environment_ci)}/bom"226 end227 def pack_design_ns_path(source, pack, version)228 "/public/#{source}/packs/#{pack}/#{version}"229 end230 def platform_pack_design_ns_path(platform)231 return platform.nsPath if platform.ciClassName.start_with?('mgmt.')232 platform_attr = platform.ciAttributes233 pack_design_ns_path(platform_attr.source, platform_attr.pack, platform_attr.version)234 end235 def platform_pack_ns_path(platform)236 ci_class_name = platform.ciClassName237 if ci_class_name.start_with?('mgmt.')238 platform.nsPath239 elsif ci_class_name.end_with?('catalog.Platform')240 platform_pack_design_ns_path(platform)241 else242 platform_pack_transition_ns_path(platform)243 end244 end245 def pack_transition_ns_path(source, pack, version, availability)246 "/public/#{source}/packs/#{pack}/#{version}/#{availability.downcase}"247 end248 def platform_pack_transition_ns_path(platform)249 platform_attr = platform.ciAttributes250 pack_transition_ns_path(platform_attr.source, platform_attr.pack, platform_attr.version, platform.ciAttributes.availability.downcase)251 end252 def design_platform_ns_path(assembly_ci, platform_ci)253 "#{assembly_ns_path(assembly_ci)}/_design/#{platform_ci.ciName}"254 end255 def transition_platform_ns_path(environment_ci, platform_ci)256 "#{environment_manifest_ns_path(environment_ci)}/#{platform_ci.ciName}/#{platform_ci.ciAttributes.major_version}"257 end258 def bom_platform_ns_path(environment_ci, platform_ci)259 "#{environment_bom_ns_path(environment_ci)}/#{platform_ci.ciName}/#{platform_ci.ciAttributes.major_version}"260 end261 def token_ns_path(token_ci)262 "#{token_ci.nsPath}/#{token_ci.ciName}"263 end264 def locate_catalog_design(design_id)265 Cms::Ci.locate(design_id, catalog_designs_ns_path, 'account.Design') ||266 Cms::Ci.locate(design_id, private_catalog_designs_ns_path, 'account.Design')267 end268 def locate_cloud(id)269 cloud = Cms::Ci.locate(id, clouds_ns_path, 'account.Cloud')270 cloud = nil if cloud && cloud.ciClassName != 'account.Cloud'271 return cloud272 end273 def locate_assemblies274 assemblies = Cms::Relation.all(:params => {:targetClassName => 'account.Assembly',275 :direction => 'from',276 :ciId => current_user.organization.cms_id}).map(&:toCi)277 return assemblies if is_admin? || has_org_scope?278 allowed = current_user.organization.ci_proxies.joins(:teams).279 where(:ns_path => organization_ns_path).280 where('teams.id IN (?)', current_user.all_team_ids).pluck(:ci_id).inject({}) do |m, ci_id|281 m[ci_id] = true282 m283 end284 return assemblies.select { |a| allowed[a.ciId] }285 end286 def locate_assembly(id)287 assembly = Cms::Ci.locate(id, organization_ns_path, 'account.Assembly')288 if read_only_request?289 unless is_admin? || has_org_scope? ||290 current_user.organization.ci_proxies.joins(:teams).291 where(:ns_path => organization_ns_path, :ci_id => assembly.ciId).292 where('teams.id IN (?)', current_user.all_team_ids).first293 raise UnauthorizedException.new294 end295 else296 raise UnauthorizedException.new unless dto_allowed?(assembly.ciId)297 end298 return assembly299 end300 # This is default implementation to indicate which request considered read access only. Overwrite this301 # in controllers to provide custom logic in lieu of default which treats all GET requests as read-only.302 # E.g. some actions may be defined as POST (e.g. due URL length limitation of GET requests) so you can303 # use this method to mark them read-only.304 def read_only_request?305 request.get?306 end307 def locate_environment(id, assembly)308 Cms::Ci.locate(id, assembly_ns_path(assembly), 'manifest.Environment')309 end310 def locate_catalog_design_platform(qualifier, design, opts = {})311 Cms::Ci.locate(qualifier, catalog_design_ns_path(design), 'catalog.Platform', opts)312 end313 def locate_pack_platform(qualifier, source, pack, version, availability = nil, opts = {})314 if availability.blank?315 Cms::Ci.locate(qualifier, pack_design_ns_path(source, pack, version), 'mgmt.catalog.Platform', opts)316 else317 Cms::Ci.locate(qualifier, pack_transition_ns_path(source, pack, version, availability), 'mgmt.manifest.Platform', opts)318 end319 end320 def locate_pack_for_platform(platform)321 attrs = platform.ciAttributes322 locate_pack(attrs.source, attrs.pack)323 end324 def locate_pack(source, pack)325 Cms::Ci.first(:params => {:nsPath => "/public/#{source}/packs",326 :ciClassName => 'mgmt.Pack',327 :ciName => pack})328 end329 def locate_pack_version_for_platform(platform)330 attrs = platform.ciAttributes331 locate_pack_version(attrs.source, attrs.pack, attrs.version)332 end333 def locate_pack_version(source, pack, version)334 Cms::Ci.first(:params => {:nsPath => "/public/#{source}/packs/#{pack}",335 :ciClassName => 'mgmt.Version',336 :ciName => version,337 :includeAltNs => Catalog::PacksController::ORG_VISIBILITY_ALT_NS_TAG})338 end339 def locate_design_platform(qualifier, assembly, opts = {})340 Cms::DjCi.locate(qualifier, assembly_ns_path(assembly), 'catalog.Platform', opts)341 end342 def locate_manifest_platform(qualifier, environment, opts = {})343 dj = opts.delete(:dj)344 dj = true if dj.nil?345 clazz = dj ? Cms::DjCi : Cms::Ci346 if qualifier =~ /\D/347 ci_name, version = qualifier.split('!')348 if version.present?349 result = clazz.locate(ci_name,350 "#{environment_manifest_ns_path(environment)}/#{ci_name}/#{version}",351 'manifest.Platform',352 opts)353 else354 result = clazz.locate(ci_name,355 "#{environment_manifest_ns_path(environment)}/#{ci_name}",356 'manifest.Platform',357 opts.merge(:recursive => true)) {|a| a.find {|p| p.ciAttributes.is_active == 'true'}}358 end359 else360 # ciId361 result = clazz.locate(qualifier, nil, nil, opts)362 end363 result364 end365 def locate_ci_in_platform_ns(qualifier, platform, ci_class_name = nil, opts = {}, &block)366 ns_path = (in_design? || in_catalog?) ? "#{platform.nsPath}/_design/#{platform.ciName}" : platform.nsPath367 ci = Cms::DjCi.locate(qualifier, ns_path, ci_class_name, opts, &block)368 ci.add_policy_locations(platform_pack_ns_path(platform))369 return ci370 end371 def locate_component_in_manifest_ns(component_id, platform, class_name = nil, opts = {})372 locate_ci_in_platform_ns(component_id, platform, class_name, opts) do |results|373 results.find { |ci| !%w(Platform Attachment Monitor Localvar).include?(ci.ciClassName.split('.').last) }374 end375 end376 def locate_cloud_service_template(service)377 service_class_name = service.ciClassName378 if service_class_name.start_with?('cloud.zone.service')379 Cms::Ci.build(:ciClassName => service_class_name)380 else381 Cms::Ci.first(:params => {:nsPath => '/public/',382 :recursive => true,383 :ciClassName => "mgmt.#{service_class_name}",384 :ciName => service.ciName})385 end386 end387 def calculate_attr_diff(target, base)388 attributes_key = target.is_a?(Cms::Ci) ? :ciAttributes : :relationAttributes389 base_attrs = base ? base.send(attributes_key).attributes : {}390 attrs = target.send(attributes_key).attributes391 target.meta.attributes[:mdAttributes].inject([]) do |diff, a|392 attr_name = a.attributeName393 attr_value = attrs[attr_name]394 pack_attr_value = base_attrs[attr_name]395 unless attr_value == pack_attr_value || ((attr_value.nil? || attr_value.empty?) && (pack_attr_value.nil? || pack_attr_value.empty?))396 diff << {:attribute => attr_name, :value => attr_value, :base_value => pack_attr_value}397 end398 diff399 end400 end401 def execute(model, operation, *args)402 execute_nested(model, model, operation, *args)403 end404 def execute_nested(parent_model, model, operation, *args)405 begin406 result = model.send(operation, *args)407 rescue Exception => e408 handle_error e, parent_model409 result = false410 end411 model.errors.full_messages.each {|e| parent_model.errors.add(:base, e)} unless parent_model == model412 return result413 end414 def handle_error(exception, record)415 message = exception.message416 body = exception.respond_to?(:response) ? exception.response.body : nil417 if body418 begin419 message_hash = ActiveSupport::JSON.decode(body)420 message = "#{message_hash['message'].presence || exception.message} (#{message_hash['code']})"421 rescue Exception => e422 message = 'unknown reason.'423 end424 end425 record.errors.add(:base, message.size > 300 ? "#{message[0...300]} ..." : message)426 logger.error '-------------- cms EXCEPTION --------------'427 logger.error(body) if body428 logger.error(exception)429 logger.error(exception.backtrace.join("\n\t"))430 logger.error '-------------------------------------------'431 end432 def handle_generic_exception(exception)433 if exception.is_a?(SocketError) || exception.is_a?(Errno::ECONNREFUSED)434 redirect_to error_url(:message => 'CMS is not accessible.')435 return436 end437 @exception = exception438 redirect = Rails.application.config.consider_all_requests_local439 if redirect440 raise(exception)441 else442 logger.error '-------------- EXCEPTION --------------'443 logger.error(exception)444 logger.error(exception.backtrace.join("\n\t"))445 logger.error '-------------------------------------------'446 if request.xhr?447 render :js => '', :status => :internal_server_error448 elsif request.format == :html449 redirect_to (user_signed_in? ? error_redirect_path : new_user_session_path)450 # redirect_to (user_signed_in? ? '/500' : new_user_session_path)451 elsif request.format == :json452 render :json => {:code => 500, :exception => exception.to_s}, :status => :internal_server_error453 else454 render :status => :internal_server_error455 end456 end457 end458 def set_no_cache459 response.headers['Cache-Control'] = 'no-cache, no-store, max-age=0, must-revalidate'460 response.headers['Pragma'] = 'no-cache'461 response.headers['Expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT'462 end463 def cors_check464 cors_headers465 render :nothing => true, :status => :ok466 end467 def cors_headers468 headers['Access-Control-Allow-Origin'] = '*'469 headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'470 headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Token, Authorization, Content-Type, Accept'471 headers['Access-Control-Max-Age'] = '86400'472 # headers['Access-Control-Max-Age'] = '1'473 end474 def configure_permitted_parameters475 devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation, :remember_me, :show_wizard, :name) }476 devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email, :password, :password_confirmation, :remember_me, :show_wizard, :name) }477 devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :email, :password, :password_confirmation, :current_password, :show_wizard, :name) }478 end479 def authenticate_user_from_token480 return unless request.authorization.present? && request.authorization.split(' ', 2).first == 'Basic'481 token, foo = Base64.decode64(request.authorization.split(' ', 2).last || '').split(/:/, 2)482 user = token.present? && User.where(:authentication_token => token.to_s).first483 request.env["devise.skip_trackable"] = true # do not update user record with "trackable" stats (i.e. sign_in_count, last_sign_in_at, etc...) for API requests.484 # Passing in store => false, so the user is not actually stored in the session and a token is needed for every request.485 sign_in(user, store: false) if user486 request.env["devise.skip_trackable"] = false487 end488 def check_username489 return if request.authorization.present?490 if user_signed_in?491 if current_user.username != session[:username]492 logger.error "Current username '#{current_user.username}' doesn't match session: #{session.inspect}"493 sign_out494 message = 'Please verify your identity by signing in.'495 flash.now[:alert] = message496 respond_to do |format|497 format.html { redirect_to new_user_session_url}498 format.js { render :js => "window.location = '#{new_user_session_url}'" }499 format.json { render :json => {:errors => [message]}, :status => :unauthorized }500 end501 return502 end503 # Limit to only one GUI session per user.504 unless request.format == :json || session[:token] == current_user.session_token505 sign_out506 message = 'You are already logged in somewhere else. Please start new session by signing in if you would like to continue here.'507 if request.xhr?508 redirect_to new_user_session_path(:message => message)509 else510 flash[:error] = message511 redirect_to new_user_session_path, :status => :see_other512 end513 end514 end515 end516 def check_reset_password517 if user_signed_in?518 user = current_user519 if user.reset_password_token?520 sign_out521 flash[:notice] = 'Please reset your password.'522 redirect_to edit_password_url(user, :reset_password_token => user.reset_password_token), :status => :see_other523 end524 end525 end526 def set_active_resource_headers(enable = true)527 if enable && user_signed_in?528 cms_user = current_user.username529 AR_CLASSES_WITH_HEADERS.each do |clazz|530 clazz.headers['X-Cms-User'] = cms_user531 clazz.headers['X-Cms-Client'] = ENV['RAILS_ENV']532 clazz.headers['X-Cms-Scope'] = organization_ns_path if current_user.organization533 end534 else535 AR_CLASSES_WITH_HEADERS.each do |clazz|536 clazz.headers.delete('X-Cms-User')537 clazz.headers.delete('X-Cms-Client')538 clazz.headers.delete('X-Cms-Scope')539 end540 end541 end542 def clear_active_resource_headers543 set_active_resource_headers(false)544 end545 def check_eula546 return unless user_signed_in? && current_user.eula_accepted_at.blank?547 respond_to do |format|548 format.html { redirect_to show_eula_account_profile_path}549 format.js { render :js => "window.location = '#{show_eula_account_profile_path}'" }550 format.json { render :json => {:errors => ['EULA not accepted']}, :status => :unauthorized }551 end552 end553 def check_organization554 if user_signed_in?555 org_name = params[:org_name]556 if org_name.present? && !(current_user.organization && current_user.organization.name == org_name)557 org = current_user.organizations.where('organizations.name' => org_name).first558 if org559 current_user.change_organization(org)560 else561 org = Organization.where('organizations.name' => org_name).first562 if org563 unauthorized("You are not part of organization '#{org_name}'.", organization_public_profile_path(:org_name => org_name))564 else565 redirect_to not_found_path566 end567 end568 end569 end570 end571 include ActionView::Helpers::JavaScriptHelper572 def process_flash_messages573 return unless request.xhr?574 response.body += ";flash('#{escape_javascript(flash[:notice])}', '#{escape_javascript(flash[:error])}', '#{escape_javascript(flash[:alert])}');" if flash[:notice].present? || flash[:error].present? || flash[:alert].present?575 flash.discard576 end577 def rfc_action_to_color(action = '')578 case action579 when 'add'580 '#468847'581 when 'replace'582 '#468847'583 when 'update'584 '#F89406'585 when 'delete'586 '#B94A48'587 else588 '#777777'589 end590 end591 def platforms_diagram(platforms, links_to, path, size = nil)592 graph = GraphViz::new(:G)593 graph[:truecolor => true,594 :rankdir => 'TB',595 :ratio => 'fill',596 :size => size || '6,3',597 :compound => true,598 :concentrate => true,599 :bgcolor => 'transparent']600 graph.node[{:fontsize => 8,601 :fontname => 'ArialMT',602 :color => 'black',603 :fontcolor => 'black',604 :fillcolor => 'whitesmoke',605 :fixedsize => true,606 :width => '2.50',607 :height => '0.66',608 :style => 'rounded,filled'}]609 platforms.each do |r|610 platform = r.toCi611 attrs = platform.ciAttributes612 label = "<<table border='0' cellspacing='2' fixedsize='true' width='175' height='44'>"613 label << "<tr><td fixedsize='true' rowspan='2' cellpadding='4' width='40' height='36' align='center'>"614 label << "<img scale='both' src='#{GRAPHVIZ_IMG_STUB}'></img></td>"615 label << "<td align='left' cellpadding='0'><font point-size='12'><b>#{platform.ciName.truncate(18)}</b></font></td></tr>"616 label << "<tr><td align='left' cellpadding='0'><font point-size='10'>version #{"#{attrs.major_version}"}</font></td></tr>"617 label << "</table>>"618 graph.add_node(platform.ciId.to_s,619 :target => '_parent',620 :URL => "#{path}/platforms/#{platform.ciId}",621 :tooltip => "#{attrs.source}/#{attrs.pack}/#{attrs.version}",622 :label => label,623 :shape => "#{'double' if platform.ciAttributes.try(:availability) == 'redundant'}octagon",624 :color => rfc_action_to_color(platform.try(:rfcAction)),625 :fillcolor => platform.ciAttributes.try(:is_active) == 'false' ? '#CCCCCC' : r.relationAttributes.try(:enabled) == 'false' ? '#FFDDDD' : 'white')626 end627 links_to.each { |r| graph.add_edges(r.fromCiId.to_s,628 r.toCiId.to_s,629 :color => rfc_action_to_color(r.try(:rfcAction))) }630 return graph631 end632 def packs_info(org = current_user.organization.name)633 pack_versions = {}634 packs = {}635 pack_sources = Cms::Ci.all(:params => {:nsPath => '/public', :ciClassName => 'mgmt.Source'}).map(&:ciName)636 pack_map = Cms::Ci.all(:params => {:nsPath => '/public',637 :ciClassName => 'mgmt.Pack',638 :recursive => true}).inject({}) do |m, c|639 root, public, source = c.nsPath.split('/')640 m[source] ||= []641 m[source] << c642 m643 end644 versions = Cms::Ci.all(:params => {:nsPath => '/public',645 :ciClassName => 'mgmt.Version',646 :recursive => true,647 :attr => 'enabled:neq:false'})648 versions += Cms::Ci.all(:params => {:nsPath => '/public',649 :ciClassName => 'mgmt.Version',650 :recursive => true,651 :attr => 'enabled:eq:false',652 :altNsTag => Catalog::PacksController::ORG_VISIBILITY_ALT_NS_TAG,653 :altNs => organization_ns_path(org)})654 version_map = versions.inject({}) do |m, version|655 m[version.nsPath] ||= []656 m[version.nsPath] << version.ciName657 m658 end659 pack_sources.each do |source|660 pack_versions[source] = {}661 packs[source] = (pack_map[source] || []).inject({}) do |ch, pack|662 versions = version_map["#{pack.nsPath}/#{pack.ciName}"]663 if versions.present?664 pack_versions[source][pack.ciName] = versions.sort.reverse665 category = pack.ciAttributes.category666 ch[category] = [] unless ch.include?(category)667 ch[category] << [pack.ciAttributes.description, pack.ciName]668 end669 ch670 end671 end672 packs = packs.inject({}) do |m, source_packs|673 m[source_packs.first] = source_packs.last.to_a.sort_by {|e| e.first}674 m675 end676 return pack_sources, pack_versions, packs677 end678 def pack_versions(source, pack_name, major_version = nil)679 pack_ns_path = "/public/#{source}/packs/#{pack_name}"680 if check_pack_owner_group_membership?(current_user) || has_support_permission?(Catalog::PacksController::SUPPORT_PERMISSION_PACK_MANAGEMENT)681 versions = Cms::Ci.all(:params => {:nsPath => pack_ns_path,682 :ciClassName => 'mgmt.Version',683 :includeAltNs => Catalog::PacksController::ORG_VISIBILITY_ALT_NS_TAG})684 else685 versions = Cms::Ci.all(:params => {:nsPath => pack_ns_path,686 :ciClassName => 'mgmt.Version',687 :recursive => true,688 :attr => 'enabled:neq:false',689 :includeAltNs => Catalog::PacksController::ORG_VISIBILITY_ALT_NS_TAG})690 versions += Cms::Ci.all(:params => {:nsPath => pack_ns_path,691 :ciClassName => 'mgmt.Version',692 :recursive => true,693 :attr => 'enabled:eq:false',694 :altNsTag => Catalog::PacksController::ORG_VISIBILITY_ALT_NS_TAG,695 :altNs => organization_ns_path})696 end697 versions = versions.select {|v| v.ciName == major_version || v.ciName.start_with?("#{major_version}.")} if major_version.present?698 versions.sort_by { |v| s = v.ciName.split('.'); -(s[1].to_i * 100000 + s[2].to_i) }699 end700 def check_pack_owner_group_membership?(user = current_user)701 auth_group = Settings.pack_management_auth702 # 'pack_management_auth' is assumed to the name of the user group whose memebers are allowed to manage pack visibility.703 auth_group.present? && user.in_group?(auth_group)704 end705 def render_json_ci_response(ok, ci, errors = nil, status = nil)706 errors = [errors] if errors.present? && !errors.is_a?(Array)707 if ok && ci.present?708 render :json => ci, :status => :ok709 elsif ci710 render :json => {:errors => errors || ci.errors.full_messages}, :status => status || :unprocessable_entity711 else712 render :json => {:errors => errors || ['not found']}, :status => status || :not_found713 end714 end715 def default_url_options(options = {})716 (user_signed_in? && current_user.organization) ? {:org_name => current_user.organization.name} : {}717 end718 def unauthorized(message = 'Unauthorized access!', redirect_path = root_path)719 respond_to do |format|720 format.html { redirect_to redirect_path, :alert => message }721 format.js { render :js => "$j('.modal').modal('hide'); flash(null, 'Unauthorized access!')" }722 format.json { render :json => {:errors => [message]}, :status => :unauthorized }723 end724 end725 def handle_unauthorized(exception)726 unauthorized727 end728 def handle_ci_not_found(exception)729 not_found(exception.message)730 end731 def not_found(message)732 Rails.logger.warn "CI not found: #{message}"733 respond_to do |format|734 format.html {redirect_to not_found_url}735 format.js {render :status => :not_found}736 format.json {render :json => {:errors => [message]}, :status => :not_found}737 end738 end739 def is_admin?(org = nil)740 current_user.is_admin?(org)741 end742 def has_org_scope?(org = nil)743 current_user.has_org_scope?(org)744 end745 def manages_access?(org_id = nil)746 current_user.manages_access?(org_id)747 end748 def manages_access_for_cloud?(cloud_id)749 current_user.manages_access_for_cloud?(cloud_id)750 end751 def manages_access_for_assembly?(assembly_id)752 current_user.manages_access_for_assembly?(assembly_id)753 end754 def has_design?(assembly_id = @assembly.try(:ciId))755 current_user.has_design?(assembly_id)756 end757 def has_transition?(assembly_id = @assembly.try(:ciId))758 current_user.has_transition?(assembly_id)759 end760 def has_operations?(assembly_id = @assembly.try(:ciId))761 current_user.has_operations?(assembly_id)762 end763 def has_cloud_services?(cloud_id = @cloud.try(:ciId))764 current_user.has_cloud_services?(cloud_id)765 end766 def has_cloud_compliance?(cloud_id = @cloud.try(:ciId))767 current_user.has_cloud_compliance?(cloud_id)768 end769 def has_cloud_support?(cloud_id = @cloud.try(:ciId))770 current_user.has_cloud_support?(cloud_id)771 end772 def allowed_to_settle_approval?(approval)773 govern_ci = approval.govern_ci774 cloud = govern_ci.nsPath.split('/')[3]775 class_name = govern_ci.ciClassName776 return class_name == 'cloud.Support' ? has_cloud_support?(cloud) : has_cloud_compliance?(cloud)777 end778 def authorize_admin779 unauthorized unless is_admin?780 end781 def dto_allowed?(assembly_id = nil)782 return false unless user_signed_in?783 if in_design?784 return current_user.has_design?(assembly_id || @assembly.try(:ciId))785 elsif in_transition?786 current_user.has_transition?(assembly_id || @assembly.try(:ciId))787 elsif in_operations?788 current_user.has_operations?(assembly_id || @assembly.try(:ciId))789 else790 return true791 end792 end793 def path_to_ci!(ci, dto_area = nil)794 begin795 return path_to_ci(ci, dto_area)796 rescue Exception => e797 return nil798 end799 end800 def path_to_ci(ci, dto_area = nil)801 ns_path = ci.nsPath802 class_name = ci.ciClassName803 name = ci.ciName804 ci_id = ci.ciId805 if ns_path.include?('/_clouds')806 root, org, _clouds, cloud, zone_or_service_class, service_name = ns_path.split('/')807 if cloud.present?808 if class_name == 'account.Cloudvar'809 return edit_cloud_path(:org_name => org,810 :id => cloud,811 :anchor => "variables/list_item/#{ci_id}")812 elsif class_name == 'cloud.Zone'813 return edit_cloud_path(:org_name => org,814 :id => cloud,815 :anchor => "zones/list_item/#{ci_id}")816 elsif class_name.start_with?('cloud.service.')817 return edit_cloud_service_path(:org_name => org,818 :cloud_id => cloud,819 :id => ci_id)820 elsif class_name.start_with?('cloud.zone.service.')821 return edit_cloud_service_path(:org_name => org,822 :cloud_id => cloud,823 :zone_id => zone_or_service_class,824 :id => ci_id)825 elsif class_name.start_with?('cloud.compliance.')826 return edit_cloud_path(:org_name => org,827 :id => cloud,828 :anchor => "compliance/list_item/#{ci_id}")829 elsif class_name == 'cloud.Support'830 return edit_cloud_path(:org_name => org,831 :id => cloud,832 :anchor => "support/list_item/#{ci_id}")833 elsif class_name == 'cloud.Offering'834 return edit_cloud_service_path(:org_name => org,835 :cloud_id => cloud,836 :id => service_name,837 :anchor => "offerings/list_item/#{ci_id}")838 else839 return edit_cloud_service_path(:org_name => org, :cloud_id => cloud, :id => name)840 end841 elsif class_name == 'account.Cloud'842 return edit_cloud_path(ci_id)843 else844 return clouds_path(:org_name => org)845 end846 elsif class_name == 'account.Design'847 root, org, _catalog = ns_path.split('/')848 return catalog_design_path(:org_name => org, :id => ci_id)849 elsif class_name.start_with?('catalog.')850 if ns_path.include?('/_catalogs/')851 root, org, _catalogs, design, _design, platform = ns_path.split('/')852 if platform.present?853 if class_name == 'catalog.Monitor'854 return catalog_design_platform_monitor_path(:org_name => org,855 :design_id => design,856 :platform_id => platform,857 :id => ci_id)858 else859 return catalog_design_platform_component_path(:org_name => org,860 :design_id => design,861 :platform_id => platform,862 :id => name)863 end864 elsif class_name == 'catalog.Platform'865 return catalog_design_platform_path(:org_name => org, :design_id => design, :id => name)866 else867 return catalog_design_path(:org_name => org, :id => design)868 end869 else870 root, org, assembly, _design, platform = ns_path.split('/')871 if platform.present?872 if class_name == 'catalog.Localvar'873 return assembly_design_platform_path(:org_name => org,874 :assembly_id => assembly,875 :id => platform,876 :anchor => "variables/list_item/#{ci_id}")877 elsif class_name == 'catalog.Attachment'878 return assembly_design_platform_attachment_path(:org_name => org,879 :assembly_id => assembly,880 :platform_id => platform,881 :id => ci_id)882 elsif class_name == 'catalog.Monitor'883 return assembly_design_platform_monitor_path(:org_name => org,884 :assembly_id => assembly,885 :platform_id => platform,886 :id => ci_id)887 else888 return edit_assembly_design_platform_component_path(:org_name => org, :assembly_id => assembly, :platform_id => platform, :id => ci_id)889 end890 else891 if class_name == 'catalog.Platform'892 return assembly_design_platform_path(:org_name => org, :assembly_id => assembly, :id => name)893 elsif class_name == 'catalog.Globalvar'894 return assembly_design_path(:org_name => org,895 :assembly_id => assembly,896 :anchor => "variables/list_item/#{ci_id}")897 else898 return assembly_design_path(:org_name => org, :assembly_id => assembly)899 end900 end901 end902 elsif class_name.start_with?('manifest.')903 root, org, assembly, env, manifest, platform, platform_version = ns_path.split('/')904 if platform.present? && platform_version.present?905 if class_name == 'manifest.Platform'906 if dto_area == 'design'907 return assembly_design_platform_path(:org_name => org,908 :assembly_id => assembly,909 :id => name)910 elsif dto_area == 'operations'911 return assembly_operations_environment_platform_path(:org_name => org,912 :assembly_id => assembly,913 :environment_id => env,914 :id => "#{platform}!#{platform_version}")915 else916 return assembly_transition_environment_platform_path(:org_name => org,917 :assembly_id => assembly,918 :environment_id => env,919 :id => "#{platform}!#{platform_version}")920 end921 elsif class_name == 'manifest.Localvar'922 return assembly_transition_environment_platform_path(:org_name => org,923 :assembly_id => assembly,924 :environment_id => env,925 :id => "#{platform}!#{platform_version}",926 :anchor => "variables/list_item/#{ci_id}")927 elsif class_name == 'manifest.Attachment'928 return assembly_transition_environment_platform_attachment_path(:org_name => org,929 :assembly_id => assembly,930 :environment_id => env,931 :platform_id => "#{platform}!#{platform_version}",932 :id => ci_id)933 elsif class_name == 'manifest.Monitor'934 return assembly_transition_environment_platform_monitor_path(:org_name => org,935 :assembly_id => assembly,936 :environment_id => env,937 :platform_id => "#{platform}!#{platform_version}",938 :id => ci_id)939 else940 if dto_area == 'design'941 return edit_assembly_design_platform_component_path(:org_name => org,942 :assembly_id => assembly,943 :platform_id => platform,944 :id => name,945 :class_name => "catalog.#{class_name.split('.', 2).last}")946 elsif dto_area == 'operations'947 return assembly_operations_environment_platform_component_path(:org_name => org,948 :assembly_id => assembly,949 :environment_id => env,950 :platform_id => "#{platform}!#{platform_version}",951 :id => ci_id)952 else953 return edit_assembly_transition_environment_platform_component_path(:org_name => org,954 :assembly_id => assembly,955 :environment_id => env,956 :platform_id => "#{platform}!#{platform_version}",957 :id => ci_id)958 end959 end960 else961 if class_name == 'manifest.Globalvar'962 return assembly_transition_environment_path(:org_name => org,963 :assembly_id => assembly,964 :id => env,965 :anchor => "variables/list_item/#{ci_id}")966 elsif class_name.start_with?('manifest.relay')967 return assembly_transition_environment_path(:org_name => org,968 :assembly_id => assembly,969 :id => env,970 :anchor => "relays/list_item/#{ci_id}")971 else972 if dto_area == 'operations'973 return assembly_operations_environment_path(:org_name => org, :assembly_id => assembly, :id => ci_id)974 else975 return assembly_transition_environment_path(:org_name => org, :assembly_id => assembly, :id => ci_id)976 end977 end978 end979 elsif class_name.start_with?('bom.')980 root, org, assembly, env, bom, platform, platform_version = ns_path.split('/')981 if platform.present? && platform_version.present?982 return assembly_operations_environment_platform_instance_path(:org_name => org,983 :assembly_id => assembly,984 :environment_id => env,985 :platform_id => "#{platform}!#{platform_version}",986 :id => ci_id)987 else988 return assembly_operations_environment_path(:org_name => org, :assembly_id => assembly, :environment_id => env)989 end990 else991 root, org = ns_path.split('/')992 if class_name == 'account.Cloud'993 return edit_cloud_path(:org_name => org, :id => name)994 elsif class_name == 'account.Assembly'995 return assembly_path(:org_name => org, :id => name)996 elsif class_name == 'account.Environment'997 return edit_organization_path(:org_name => org, :anchor => "environments/list_item/#{ci_id}")998 elsif class_name == 'account.Policy'999 return edit_organization_path(:org_name => org, :anchor => "policies/list_item/#{ci_id}")1000 elsif class_name == 'account.Organization'1001 return edit_organization_path(:org_name => name)1002 elsif class_name.start_with?('account.notification')1003 return edit_organization_path(:org_name => org, :anchor => "notifications/list_item/#{ci_id}")1004 end1005 end1006 end1007 def path_to_ns!(ns_path, dto_area = nil)1008 begin1009 path_to_ns(ns_path, dto_area)1010 rescue Exception => e1011 return nil1012 end1013 end1014 def path_to_ns(ns_path, dto_area = nil)1015 if ns_path.include?('/_clouds')1016 root, org, _clouds, cloud, zone = ns_path.split('/')1017 if zone.present?1018 return edit_cloud_path(:org_name => org,1019 :id => cloud,1020 :anchor => 'zones')1021 elsif cloud.present?1022 return edit_cloud_path(:org_name => org, :id => cloud)1023 else1024 return clouds_path(:org_name => org)1025 end1026 elsif ns_path.include?('/_services')1027 root, org, _clouds, service = ns_path.split('/')1028 if service.present?1029 return edit_service_path(:org_name => org, :id => service)1030 else1031 return services_path(:org_name => org)1032 end1033 elsif ns_path.include?('/_catalogs')1034 root, org, _catalogs, design, _design, platform = ns_path.split('/')1035 if platform.present?1036 return catalog_design_platform_path(:org_name => org, :design_id => design, :id => platform)1037 else1038 return catalog_design_path(:org_name => org, :design_id => design)1039 end1040 elsif ns_path.include?('/_design/')1041 root, org, assembly, _design, platform = ns_path.split('/')1042 if platform.present?1043 return assembly_design_platform_path(:org_name => org, :assembly_id => assembly, :id => platform)1044 else1045 return assembly_design_path(:org_name => org, :assembly_id => assembly)1046 end1047 elsif ns_path.include?('/manifest/')1048 root, org, assembly, env, manifest, platform, platform_version = ns_path.split('/')1049 if platform.present? && platform_version.present?1050 return assembly_transition_environment_platform_path(:org_name => org,1051 :assembly_id => assembly,1052 :environment_id => env,1053 :id => "#{platform}!#{platform_version}")1054 elsif env.present?1055 return assembly_transition_environment_path(:org_name => org, :assembly_id => assembly, :id => env)1056 else1057 return assembly_transition_path(:org_name => org, :assembly_id => assembly)1058 end1059 elsif ns_path =~ (/\/bom(\/|$)/)1060 root, org, assembly, env, bom, platform, platform_version = ns_path.split('/')1061 if platform.present? && platform_version.present?1062 return assembly_operations_environment_platform_path(:org_name => org,1063 :assembly_id => assembly,1064 :environment_id => env,1065 :id => "#{platform}!#{platform_version}")1066 elsif env.present?1067 return assembly_operations_environment_path(:org_name => org, :assembly_id => assembly, :id => env)1068 else1069 return assembly_operations_path(:org_name => org, :assembly_id => assembly)1070 end1071 else1072 root, org, assembly, env = ns_path.split('/')1073 if env.present?1074 if ns_path.end_with?('/bom') || dto_area == 'operations'1075 return assembly_operations_environment_path(:org_name => org, :assembly_id => assembly, :id => env)1076 else1077 return assembly_transition_environment_path(:org_name => org, :assembly_id => assembly, :id => env)1078 end1079 elsif assembly.present?1080 return assembly_path(:org_name => org, :id => assembly)1081 elsif org.present?1082 return organization_path(:org_name => org)1083 else1084 '#'1085 end1086 end1087 end1088 def path_to_release(release)1089 root, org, assembly, env, manifest = release.nsPath.split('/')1090 if env.present?1091 assembly_transition_environment_path(:org_name => org, :assembly_id => assembly, :id => env, :anchor => "timeline/timeline_list/release_#{release.releaseId}")1092 else1093 assembly_design_path(:org_name => org, :assembly_id => assembly, :anchor => "timeline/timeline_list/release_#{release.releaseId}")1094 end1095 end1096 def path_to_deployment(deployment)1097 root, org, assembly, env, bom = deployment.nsPath.split('/')1098 assembly_transition_environment_path(:org_name => org, :assembly_id => assembly, :id => env, :anchor => "timeline/timeline_list/deployment_#{deployment.deploymentId}")1099 end1100 def set_pagination_response_headers(data)1101 add_pagination_response_headers(data.info[:total], data.info[:size], data.info[:offset]) if data1102 end1103 def add_pagination_response_headers(total_count, page_size, offset)1104 response.headers['oneops-list-total-count'] = total_count.to_s1105 response.headers['oneops-list-page-size'] = page_size.to_s1106 response.headers['oneops-list-offset'] = offset.to_s1107 end1108 def ci_image_url(ci)1109 ci_class_image_url(ci.ciClassName)1110 end1111 def ci_class_image_url(ci_class_name)1112 split = ci_class_name.split('.')1113 split = split[1..-1] if split.first == 'mgmt'1114 "#{asset_url_prefix}#{split[1..-1].join('.')}/#{split.last}.png"1115 end1116 def platform_image_url(platform)1117 ci_attrs = platform.ciAttributes1118 pack_image_url(ci_attrs.source, ci_attrs.pack, ci_attrs.version)1119 end1120 def pack_image_url(source, pack, version)1121 "#{asset_url_prefix}public/#{source}/packs/#{pack}/#{version}/#{pack}.png"1122 end1123 def graphvis_sub_ci_remote_images(svg, img_stub = GRAPHVIZ_IMG_STUB)1124 svg.scan(/(?<=xlink:title=)"[^"]+"/).inject(svg) {|r, c| r.sub(img_stub, ci_class_image_url(c[1..-2]))}1125 end1126 def graphvis_sub_pack_remote_images(svg, img_stub = GRAPHVIZ_IMG_STUB)1127 svg.scan(/(?<=xlink:title=").+\/.+\/\d+/).inject(svg) do |r, c|1128 r.sub(img_stub, pack_image_url(*c.split('/')))1129 end1130 end1131 def asset_url_prefix1132 Settings.asset_url.presence || '/cms/'1133 end1134 def browser_timezone_offset(default = 0)1135 session[:browser_timezone] || default1136 end1137 def convert_json_attrs_from_string(attrs, ci_class_name)1138 return attrs if attrs.blank?1139 types = %w(array hash struct)1140 ci_md = Cms::CiMd.look_up(ci_class_name)1141 attrs.each_pair do |k, v|1142 if v.present?1143 attr_md = ci_md.md_attribute(k)1144 if attr_md1145 if types.include?(attr_md.dataType)1146 begin1147 attrs[k] = JSON.parse(v)1148 rescue Exception => e1149 # Do nothing - leave as string.1150 end1151 end1152 end1153 end1154 end1155 end1156 def support_permissions1157 return @permissions if @permissions...
platforms_controller.rb
Source:platforms_controller.rb
...4 swagger_api :index do5 summary 'Fetches all platforms in the design of assembly.'6 notes 'This fetches all platforms from design including new platforms from open release.'7 param_org_name8 param_parent_ci_id :assembly9 response :unauthorized10 end11 def index12 @platforms = Cms::DjRelation.all(:params => {:ciId => @assembly.ciId,13 :direction => 'from',14 :relationShortName => 'ComposedOf',15 :targetClassName => 'catalog.Platform'}).map(&:toCi)16 render :json => @platforms17 end18 def show19 respond_to do |format|20 format.html do21 build_component_groups22 build_linkable_platform_map23 @policy_compliance = Cms::Ci.violates_policies(@components, false, true) if Settings.check_policy_compliance24 @release = Cms::Release.latest(:nsPath => assembly_ns_path(@assembly))25 @rfcs = @release.releaseState == 'open' ? Transistor.design_platform_rfcs(@platform.ciId, :attrProps => 'owner') : {}26 @platform_detail = Cms::CiDetail.find(@platform.ciId) unless @platform.rfcAction == 'add'27 platform_attributes = @platform.ciAttributes28 source = platform_attributes.source29 pack_name = platform_attributes.pack30 version = platform_attributes.version31 @pack_minor_versions = pack_versions(source, pack_name, version.split('.').first)32 @pack_version = @pack_minor_versions.find {|v| v.ciName == version} || locate_pack_version(source, pack_name, version)33 render(:action => :show)34 end35 format.json do36 @platform.links_to = Cms::DjRelation.all(:params => {:ciId => @platform.ciId,37 :direction => 'from',38 :relationShortName => 'LinksTo',39 :includeToCi => true}).map { |r| r.toCi.ciName } if @platform40 render_json_ci_response(true, @platform)41 end42 end43 end44 def new45 @platform = Cms::DjCi.build({:nsPath => assembly_ns_path(@assembly),46 :ciClassName => 'catalog.Platform'},47 {:owner => {}})48 respond_to do |format|49 format.html do50 build_linkable_platform_map51 render :action => :new52 end53 format.json { render_json_ci_response(true, @platform) }54 end55 end56 def create57 platform_hash = params[:cms_dj_ci].merge(:nsPath => assembly_ns_path(@assembly), :ciClassName => 'catalog.Platform')58 attrs = platform_hash[:ciAttributes]59 attrs[:major_version] = 160 attrs[:description] ||= ''61 attr_props = platform_hash.delete(:ciAttrProps)62 @platform = Cms::DjCi.build(platform_hash, attr_props)63 pack_ver = locate_pack_version_for_platform(@platform)64 if pack_ver.blank?65 @platform.errors.add(:base, 'Pack not found.')66 elsif pack_ver.ciAttributes.enabled == 'false'67 visibility = pack_ver.altNs.attributes[Catalog::PacksController::ORG_VISIBILITY_ALT_NS_TAG]68 @platform.errors.add(:base, 'Pack is disabled.') unless visibility.present? && visibility.include?(organization_ns_path)69 end70 @platform = Transistor.create_platform(@assembly.ciId, @platform) if @platform.errors.blank?71 ok = @platform.errors.blank?72 save_platform_links if ok73 respond_to do |format|74 format.html do75 if ok76 show77 else78 flash.now[:alert] = 'Failed to create platform.'79 setup_linkable_platform_map80 render :action => :new81 end82 end83 format.json { render_json_ci_response(ok, @platform) }84 end85 end86 def edit87 respond_to do |format|88 format.json { render_json_ci_response(true, @platform) }89 end90 end91 def update92 ok = execute(@platform, :update_attributes, params[:cms_dj_ci])93 ok = save_platform_links if ok94 respond_to do |format|95 format.js do96 if ok97 setup_linkable_platform_map()98 end99 render :action => :edit100 end101 format.json { render_json_ci_response(ok, @platform) }102 end103 end104 def destroy105 ok = Transistor.delete_platform(@assembly.ciId, @platform)106 respond_to do |format|107 format.html do108 flash[:error] = "Failed to delete platform. #{@platform.errors.full_messages.join('. ')}" unless ok109 redirect_to(assembly_design_path(@assembly))110 end111 format.json { render_json_ci_response(ok, @platform) }112 end113 end114 def new_clone115 @assemblies = locate_assemblies116 end117 def clone118 @to_assembly = locate_assembly(params[:to_assembly_id])119 id = Transistor.clone_platform(@platform.ciId, {:nsPath => assembly_ns_path(@to_assembly), :ciClassName => 'catalog.Platform', :ciName => params[:to_ci_name]})120 @to_platform = Cms::DjCi.find(id) if id121 ok = @to_platform.present?122 flash[:error] = "Failed to clone platform '#{@platform.ciName}'." unless ok123 respond_to do |format|124 format.js125 format.json { render_json_ci_response(ok, @to_platform, ['Failed to clone.']) }126 end127 end128 def component_types129 exising_map = Cms::DjRelation.all(:params => {:ciId => @platform.ciId,130 :direction => 'from',131 :relationShortName => 'Requires'}).inject({}) do |m, r|132 m[r.relationAttributes.template] = (m[r.relationAttributes.template] || 0) + 1133 m134 end135 result = get_platform_requires_relation_temlates(@platform).inject({}) do |m, r|136 template_name = r.toCi.ciName.split('::').last137 cardinality = r.relationAttributes.constraint.gsub('*', '999').split('..')138 existing_count = exising_map[template_name] || 0139 m[template_name] = {:min => cardinality.first.to_i,140 :max => cardinality.last.to_i,141 :current => existing_count} unless r.toCi.ciState == 'pending_deletion' && existing_count == 0142 m143 end144 render :json => result145 end146 def diff147 clazz = params[:committed] == 'true' ? Cms::Relation : Cms::DjRelation148 changes_only = params[:changes_only] != 'false'149 # Compare components.150 platform_pack_ns_path = platform_pack_design_ns_path(@platform)151 pack_components = Cms::Relation.all(:params => {:nsPath => platform_pack_ns_path,152 :relationShortName => 'Requires',153 :includeFromCi => false,154 :includeToCi => true}).map(&:toCi).to_map(&:ciName)155 component_id_map = {}156 @diff = clazz.all(:params => {:ciId => @platform.ciId,157 :direction => 'from',158 :relationShortName => 'Requires',159 :attrProps => 'owner'}).inject([]) do |m, r|160 component = r.toCi161 component_id_map[component.ciId] = component162 pack_component = pack_components[r.relationAttributes.template]163 diff = calculate_attr_diff(component, pack_component)164 # The last condition below is to ensure that we include current component as diff when it is not required by165 # the pack (lower bound of cardinality constraint is zero) even it did not override any defaults when added by user.166 if !changes_only || diff.present? || r.relationAttributes.constraint.split('..').first.to_i == 0167 component.diffCi = pack_component168 component.diffAttributes = diff169 m << component170 end171 m172 end173 # Compare variables.174 pack_variables = Cms::Relation.all(:params => {:nsPath => platform_pack_ns_path,175 :relationShortName => 'ValueFor',176 :includeFromCi => true,177 :includeToCi => false}).map(&:fromCi).to_map(&:ciName)178 clazz.all(:params => {:ciId => @platform.ciId,179 :direction => 'to',180 :relationShortName => 'ValueFor',181 :includeFromCi => true,182 :includeToCi => false,183 :attrProps => 'owner'}).inject(@diff) do |m, r|184 variable = r.fromCi185 pack_variable = pack_variables[variable.ciName]186 diff = calculate_attr_diff(variable, pack_variable)187 # The last condition below is to ensure that we include current variable as diff when it was in the pack188 # even it does not have any attributes (namely, 'value') set.189 if !changes_only || diff.present? || !pack_variable190 variable.diffCi = pack_variable191 variable.diffAttributes = diff192 m << variable193 end194 m195 end196 # Compare monitors.197 pack_monitors = Cms::Relation.all(:params => {:nsPath => platform_pack_ns_path,198 :relationShortName => 'WatchedBy',199 :includeFromCi => false,200 :includeToCi => true}).map(&:toCi).to_map(&:ciName)201 clazz.all(:params => {:nsPath => design_platform_ns_path(@assembly, @platform),202 :relationShortName => 'WatchedBy',203 :includeFromCi => false,204 :includeToCi => true,205 :attrProps => 'owner'}).inject(@diff) do |m, r|206 monitor = r.toCi207 component = component_id_map[r.fromCiId]208 pack_monitor = pack_monitors[monitor.ciName.sub("#{@platform.ciName}-#{component.ciName}-", '')]209 diff = calculate_attr_diff(monitor, pack_monitor)210 if !changes_only || diff.present? || !pack_monitor211 monitor.diffCi = pack_monitor212 monitor.diffAttributes = diff213 monitor.component = component214 m << monitor215 end216 m217 end218 # There are no attachments in the pack so all attachments are added to diff.219 clazz.all(:params => {:nsPath => design_platform_ns_path(@assembly, @platform),220 :relationShortName => 'EscortedBy',221 :includeFromCi => true,222 :includeToCi => true,223 :attrProps => 'owner'}).inject(@diff) do |m, r|224 attachment = r.toCi225 attachment.diffCi = nil226 attachment.diffAttributes = calculate_attr_diff(attachment, Cms::Ci.build(:ciClassName => 'catalog.Attachment'))227 attachment.component = component_id_map[r.fromCiId]228 @diff << attachment229 end230 respond_to do |format|231 format.js232 format.json {render :json => @diff}233 end234 end235 def commit236 ok, @error = Transistor.commit_design_platform_rfcs(@platform.ciId, params[:desc])237 respond_to do |format|238 format.js239 format.json {render_json_ci_response(ok, @platform, ok ? nil : [@error])}240 end241 end242 def discard243 ok, @error = Transistor.discard_design_platform_rfcs(@platform.ciId)244 respond_to do |format|245 format.js {render :action => :commit}246 format.json {render_json_ci_response(ok, @platform, ok ? nil : [@error])}247 end248 end249 def pack_refresh250 if Cms::Rfc.count(design_platform_ns_path(@assembly, @platform)).values.sum > 0251 ok = false252 message = 'Pull Pack is not allowed with pending platform changes in the current release. Please commit or discard current platform changes before proceeding with pack pull.'253 else254 ok, message = Transistor.pack_refresh(@platform.ciId)255 end256 respond_to do |format|257 format.html do258 flash[:error] = message unless ok259 redirect_to :action => :show260 end261 format.json {render_json_ci_response(ok, @platform, ok ? nil : [message])}262 end263 end264 def pack_update265 if Cms::Rfc.count(design_platform_ns_path(@assembly, @platform)).values.sum > 0266 ok = false267 message = 'Pack Update is not allowed with pending platform changes in the current release. Please commit or discard current platform changes before proceeding with pack update.'268 else269 ok, message = Transistor.pack_update(@platform.ciId, params[:version])270 end271 respond_to do |format|272 format.html do273 flash[:error] = message unless ok274 redirect_to :action => :show275 end276 format.json {render_json_ci_response(ok, @platform, ok ? nil : [message])}277 end278 end279 private280 def find_assembly_and_platform281 @assembly = locate_assembly(params[:assembly_id])282 platform_id = params[:id]283 @platform = locate_design_platform(platform_id, @assembly, :attrProps => 'owner') if platform_id.present?284 end285 def build_linkable_platform_map286 if @platform.new_record?287 linkable_platform_map = find_all_platforms.inject({}) { |m, p| m[p] = false; m }288 else289 platform_ci_id = @platform.ciId290 platforms = find_all_platforms.to_map(&:ciId)291 links_to_relations = Cms::DjRelation.all(:params => {:nsPath => @platform.nsPath,292 :fromClassName => 'catalog.Platform',293 :toClassName => 'catalog.Platform',294 :relationName => 'catalog.LinksTo'})295 @links_from = []296 @links_to = []297 links_to_relations.each do |r|298 @links_from << platforms[r.fromCiId] if r.toCiId == platform_ci_id299 @links_to << platforms[r.toCiId] if r.fromCiId == platform_ci_id300 end301 linked_platform_ids = find_linked_platform_ids(links_to_relations, platform_ci_id)302 linked_platform_ids << platform_ci_id303 linked_platform_ids.uniq!304 linkable_platform_map = platforms.values.reject {|p| linked_platform_ids.include?(p.ciId) }.inject({}) do |m, p|305 m[p] = links_to_relations.find {|r| r.fromCiId == platform_ci_id && r.toCiId == p.ciId}306 m307 end308 end309 @linkable_platform_map = linkable_platform_map310 end311 def setup_linkable_platform_map312 new_links_to_ids = (params[:links_to].presence || []).map(&:to_i)313 build_linkable_platform_map314 @linkable_platform_map.keys.each { |p| @linkable_platform_map[p] = new_links_to_ids.include?(p.ciId) }315 end316 def find_all_platforms317 Cms::DjCi.all(:params => {:nsPath => @platform.nsPath, :ciClassName => 'catalog.Platform'})318 end319 def find_linked_platform_ids(relations, platform_ids)320 result = []321 platform_ids = [ platform_ids ] unless platform_ids.is_a?(Array)322 platform_ids.each do |p_id|323 relations.each { |r| result << r.fromCiId if r.toCiId == p_id }324 end325 result += find_linked_platform_ids(relations, result) if result.present?326 return result327 end328 def save_platform_links329 new_links_to_ids = (params[:links_to].presence || []).map do |id|330 begin331 Cms::DjCi.locate(id, assembly_ns_path(@assembly), 'catalog.Platform').ciId.to_i332 rescue333 nil334 end335 end336 new_links_to_ids.compact!337 old_links_to_relations = Cms::DjRelation.all(:params => {:ciId => @platform.ciId, :direction => 'from', :relationName => 'catalog.LinksTo'})338 old_links_to_ids = old_links_to_relations.map(&:toCiId)339 ok = true340 # Destroy relations to platforms that became unlinked.341 (old_links_to_ids - new_links_to_ids).each do |platform_id|342 relation = old_links_to_relations.detect { |r| r.toCiId == platform_id }343 ok = execute_nested(@platform, relation, :destroy)344 break unless ok345 end346 # Create relations to platforms that became linked.347 if ok348 (new_links_to_ids - old_links_to_ids).each do |platform_id|349 relation = Cms::DjRelation.build({:nsPath => @platform.nsPath,350 :relationName => 'catalog.LinksTo',351 :fromCiId => @platform.ciId,352 :toCiId => platform_id})353 ok = execute_nested(@platform, relation, :save)354 break unless ok355 end356 end357 return ok358 end359end...
after.rb
Source:after.rb
...6 attachments = node.workorder.payLoad.EscortedBy7 after = Array.new8 attachments.each do |a|9 if attribute_to_look =='run_on'10 a[:ciAttributes][attribute_to_look].split(",").each do |r|11 after.push(a) if ["#{run_on_event}-#{action_name}"].index(r)12 end13 else14 run_on_actions = JSON.parse(a[:ciAttributes][attribute_to_look])15 run_on_actions.each do |r|16 after.push(a) if ["#{run_on_event}-#{action_name}"].index(r)17 end18 end19 end20 after.sort_by { |a| a[:ciAttributes][:priority] }.each do |a|21 Chef::Log.info("Loading after-#{action_name} attachment #{a[:ciName]}")22 _path = a[:ciAttributes][:path] or "/tmp/#{a[:ciName]}"23 _d = File.dirname(_path)24 directory "#{_d}" do25 owner "root" unless windows_platform26 group "root" unless windows_platform27 mode "0755" unless windows_platform28 recursive true29 action :create30 not_if { File.directory?(_d) }31 end32 _source = a[:ciAttributes][:source]33 if _source.nil? || _source.empty?34 _content = a[:ciAttributes][:content]35 file "#{_path}" do36 content _content.gsub(/\r\n?/,"\n")37 owner "root" unless windows_platform38 group "root" unless windows_platform39 mode "0755" unless windows_platform40 action :create41 end42 else43 _user = a[:ciAttributes][:basic_auth_user]44 _password = a[:ciAttributes][:basic_auth_password]45 _headers = a[:ciAttributes][:headers]46 _headers = _headers.empty? ? Hash.new : JSON.parse(_headers)47 _checksum = a[:ciAttributes][:checksum] or nil48 shared_download_http "#{_source}" do49 path _path50 checksum _checksum51 headers(_headers) if _headers52 basic_auth_user _user.empty? ? nil : _user53 basic_auth_password _password.empty? ? nil : _password54 # action :nothing55 action :create56 not_if do _source =~ /s3:\/\// end57 end58 shared_s3_file "#{_source}" do59 source _source60 path _path61 access_key_id _user62 secret_access_key _password63 owner "root" unless windows_platform64 group "root" unless windows_platform65 mode 0644 unless windows_platform66 action :create67 only_if do _source =~ /s3:\/\// end68 end69 end70 if a[:ciAttributes].has_key?("exec_cmd")71 _exec_cmd = a[:ciAttributes][:exec_cmd].gsub(/\r\n?/,"\n")72 if windows_platform73 batch "execute after-#{action_name} #{a[:ciName]} attachment" do74 code <<-EOH75 #{_exec_cmd}76 EOH77 not_if { _exec_cmd.empty? }78 end79 else80 bash "execute after-#{action_name} #{a[:ciName]} attachment" do81 code <<-EOH82 #{_exec_cmd}83 EOH84 not_if { _exec_cmd.empty? }85 end86 end87 end88 end89end...
before.rb
Source:before.rb
...5 attachments = node.workorder.payLoad.EscortedBy6 before = Array.new7 attachments.each do |a|8 if attribute_to_look =='run_on'9 a[:ciAttributes][attribute_to_look].split(",").each do |r|10 before.push(a) if ["#{run_on_event}-#{action_name}"].index(r)11 end12 else13 run_on_actions = JSON.parse(a[:ciAttributes][attribute_to_look])14 run_on_actions.each do |r|15 before.push(a) if ["#{run_on_event}-#{action_name}"].index(r)16 end17 end18 end19before.sort_by { |a| a[:ciAttributes][:priority] }.each do |a|20 Chef::Log.info("Loading #{run_on_event}-#{action_name} attachment #{a[:ciName]}")21 _path = a[:ciAttributes][:path] or "/tmp/#{a[:ciName]}"22 _d = File.dirname(_path)23 directory "#{_d}" do24 owner "root" unless windows_platform25 group "root" unless windows_platform26 mode "0755" unless windows_platform27 recursive true28 action :create29 not_if { File.directory?(_d) }30 end31 _source = a[:ciAttributes][:source]32 if _source.empty?33 _content = a[:ciAttributes][:content]34 file "#{_path}" do35 content _content.gsub(/\r\n?/,"\n")36 owner "root" unless windows_platform37 group "root" unless windows_platform38 mode "0755" unless windows_platform39 action :create40 end41 else42 _user = a[:ciAttributes][:basic_auth_user]43 _password = a[:ciAttributes][:basic_auth_password]44 _headers = a[:ciAttributes][:headers]45 _headers = _headers.empty? ? Hash.new : JSON.parse(_headers)46 _checksum = a[:ciAttributes][:checksum] or nil47 shared_download_http "#{_source}" do48 path _path49 checksum _checksum50 headers(_headers) if _headers51 basic_auth_user _user.empty? ? nil : _user52 basic_auth_password _password.empty? ? nil : _password53 # action :nothing54 action :create55 not_if do _source =~ /s3:\/\// end56 end57 shared_s3_file "#{_source}" do58 source _source59 path _path60 access_key_id _user61 secret_access_key _password62 owner "root" unless windows_platform63 group "root" unless windows_platform64 mode 0644 unless windows_platform65 action :create66 only_if do _source =~ /s3:\/\// end67 end68 end69 if a[:ciAttributes].has_key?("exec_cmd")70 _exec_cmd = a[:ciAttributes][:exec_cmd].gsub(/\r\n?/,"\n")71 if windows_platform72 batch "execute #{run_on_event}-#{action_name} #{a[:ciName]} attachment" do73 code <<-EOH74 #{_exec_cmd}75 EOH76 not_if { _exec_cmd.empty? }77 end78 else79 bash "execute #{run_on_event}-#{action_name} #{a[:ciName]} attachment" do80 code <<-EOH81 #{_exec_cmd}82 EOH83 not_if { _exec_cmd.empty? }84 end85 end86 end87 end88end...
ci
Using AI Code Generation
1ci.set_name('CodeIgniter')2ci.set_version('2.1.4')3ci.set_release_date('2013-06-20')4ci.set_category('Framework')5ci.set_license('MIT')6ci.set_url('http://ellislab.com/codeigniter')7ci.set_description('CodeIgniter is a powerful PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications.')8ci.set_author('EllisLab, Inc.')9ci.set_author_url('http://ellislab.com/')10ci.set_download_url('
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!