Class: Puppet::ModuleTool::Applications::Upgrader

Inherits:
Application show all
Includes:
Errors, Shared
Defined in:
lib/puppet/module_tool/applications/upgrader.rb

Constant Summary

Constants inherited from Application

Application::DOCPATTERN

Constants included from Util

Util::AbsolutePathPosix, Util::AbsolutePathWindows, Util::DEFAULT_POSIX_MODE, Util::DEFAULT_WINDOWS_MODE, Util::RFC_3986_URI_REGEX

Constants included from Util::SymbolicFileMode

Util::SymbolicFileMode::SetGIDBit, Util::SymbolicFileMode::SetUIDBit, Util::SymbolicFileMode::StickyBit, Util::SymbolicFileMode::SymbolicMode, Util::SymbolicFileMode::SymbolicSpecialToBit

Constants included from Util::POSIX

Util::POSIX::LOCALE_ENV_VARS, Util::POSIX::USER_ENV_VARS

Instance Attribute Summary

Attributes inherited from Application

#command_line, #options

Instance Method Summary collapse

Methods included from Shared

#add_module_name_constraints_to_graph, #annotated_version, #download_tarballs, #forced?, #get_local_constraints, #get_remote_constraints, #implicit_version, #resolve_constraints

Methods inherited from Application

[], #app_defaults, available_application_names, banner, clear!, clear?, clear_everything_for_tests, #configure_indirector_routes, controlled_run, #deprecate, #deprecated?, environment_mode, exit, find, get_environment_mode, #handle_logdest_arg, #handlearg, #help, #initialize_app_defaults, interrupted?, #log_runtime_environment, #main, #name, option, option_parser_commands, #parse_options, #preinit, restart!, restart_requested?, #run_command, run_mode, #set_log_level, #setup, #setup_logs, stop!, stop_requested?, #summary, try_load_class

Methods included from Util

absolute_path?, benchmark, chuser, clear_environment, default_env, deterministic_rand, deterministic_rand_int, exit_on_fail, get_env, get_environment, logmethods, merge_environment, path_to_uri, pretty_backtrace, replace_file, safe_posix_fork, set_env, symbolizehash, thinmark, uri_encode, uri_query_encode, uri_to_path, which, withenv, withumask

Methods included from Util::SymbolicFileMode

#normalize_symbolic_mode, #symbolic_mode_to_int, #valid_symbolic_mode?

Methods included from Util::POSIX

#get_posix_field, #gid, groups_of, #idfield, #methodbyid, #methodbyname, #search_posix_field, #uid

Constructor Details

#initialize(name, options) ⇒ Upgrader


15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/puppet/module_tool/applications/upgrader.rb', line 15

def initialize(name, options)
  super(options)

  @action              = :upgrade
  @environment         = options[:environment_instance]
  @name                = name
  @ignore_changes      = forced? || options[:ignore_changes]
  @ignore_dependencies = forced? || options[:ignore_dependencies]

  SemanticPuppet::Dependency.add_source(installed_modules_source)
  SemanticPuppet::Dependency.add_source(module_repository)
end

Instance Method Details

#runObject


28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/puppet/module_tool/applications/upgrader.rb', line 28

def run
  # Disallow anything that invokes md5 to avoid un-friendly termination due to FIPS
  raise _("Module upgrade is prohibited in FIPS mode.") if Facter.value(:fips_enabled)

  name = @name.tr('/', '-')
  version = options[:version] || '>= 0.0.0'

  results = {
    :action => :upgrade,
    :requested_version => options[:version] || :latest,
  }

  begin
    all_modules = @environment.modules_by_path.values.flatten
    matching_modules = all_modules.select do |x|
      x.forge_name && x.forge_name.tr('/', '-') == name
    end

    if matching_modules.empty?
      raise NotInstalledError, results.merge(:module_name => name)
    elsif matching_modules.length > 1
      raise MultipleInstalledError, results.merge(:module_name => name, :installed_modules => matching_modules)
    end

    installed_release = installed_modules[name]

    # `priority` is an attribute of a `SemanticPuppet::Dependency::Source`,
    # which is delegated through `ModuleRelease` instances for the sake of
    # comparison (sorting). By default, the `InstalledModules` source has
    # a priority of 10 (making it the most preferable source, so that
    # already installed versions of modules are selected in preference to
    # modules from e.g. the Forge). Since we are specifically looking to
    # upgrade this module, we don't want the installed version of this
    # module to be chosen in preference to those with higher versions.
    #
    # This implementation is suboptimal, and since we can expect this sort
    # of behavior to be reasonably common in Semantic, we should probably
    # see about implementing a `ModuleRelease#override_priority` method
    # (or something similar).
    def installed_release.priority
      0
    end

    mod = installed_release.mod
    results[:installed_version] = SemanticPuppet::Version.parse(mod.version)
    dir = Pathname.new(mod.modulepath)

    vstring = mod.version ? "v#{mod.version}" : '???'
    Puppet.notice _("Found '%{name}' (%{version}) in %{dir} ...") % { name: name, version: colorize(:cyan, vstring), dir: dir }
    unless @ignore_changes
      changes = Checksummer.run(mod.path) rescue []
      if mod.has_metadata? && !changes.empty?
        raise LocalChangesError,
          :action            => :upgrade,
          :module_name       => name,
          :requested_version => results[:requested_version],
          :installed_version => mod.version
      end
    end

    Puppet::Forge::Cache.clean

    # Ensure that there is at least one candidate release available
    # for the target package.
    available_versions = module_repository.fetch(name)
    if available_versions.empty?
      raise NoCandidateReleasesError, results.merge(:module_name => name, :source => module_repository.host)
    elsif results[:requested_version] != :latest
      requested = Puppet::Module.parse_range(results[:requested_version])
      unless available_versions.any? {|m| requested.include? m.version}
        raise NoCandidateReleasesError, results.merge(:module_name => name, :source => module_repository.host)
      end
    end

    Puppet.notice _("Downloading from %{host} ...") % { host: module_repository.host }
    if @ignore_dependencies
      graph = build_single_module_graph(name, version)
    else
      graph = build_dependency_graph(name, version)
    end

    unless forced?
      add_module_name_constraints_to_graph(graph)
    end

    installed_modules.each do |installed_module, release|
      installed_module = installed_module.tr('/', '-')
      next if installed_module == name

      version = release.version

      unless forced?
        # Since upgrading already installed modules can be troublesome,
        # we'll place constraints on the graph for each installed
        # module, locking it to upgrades within the same major version.
        installed_range = ">=#{version} #{version.major}.x"
        graph.add_constraint('installed', installed_module, installed_range) do |node|
          Puppet::Module.parse_range(installed_range).include? node.version
        end

        release.mod.dependencies.each do |dep|
          dep_name = dep['name'].tr('/', '-')

          range = dep['version_requirement']
          graph.add_constraint("#{installed_module} constraint", dep_name, range) do |node|
            Puppet::Module.parse_range(range).include? node.version
          end
        end
      end
    end

    begin
      Puppet.info _("Resolving dependencies ...")
      releases = SemanticPuppet::Dependency.resolve(graph)
    rescue SemanticPuppet::Dependency::UnsatisfiableGraph
      raise NoVersionsSatisfyError, results.merge(:requested_name => name)
    end

    releases.each do |rel|
      mod = installed_modules_source.by_name[rel.name.split('-').last]
      if mod
        next if mod.has_metadata? && mod.forge_name.tr('/', '-') == rel.name

        if rel.name != name
          dependency = {
            :name => rel.name,
            :version => rel.version
          }
        end

        raise InstallConflictError,
          :requested_module  => name,
          :requested_version => options[:version] || 'latest',
          :dependency        => dependency,
          :directory         => mod.path,
          :metadata          => mod.
      end
    end

    child = releases.find { |x| x.name == name }

    unless forced?
      if child.version == results[:installed_version]
        versions = graph.dependencies[name].map { |r| r.version }
        newer_versions = versions.select { |v| v > results[:installed_version] }

        raise VersionAlreadyInstalledError,
          :module_name       => name,
          :requested_version => results[:requested_version],
          :installed_version => results[:installed_version],
          :newer_versions    => newer_versions,
          :possible_culprits => installed_modules_source.fetched.reject { |x| x == name }
      elsif child.version < results[:installed_version]
        raise DowngradingUnsupportedError,
          :module_name       => name,
          :requested_version => results[:requested_version],
          :installed_version => results[:installed_version]
      end
    end

    Puppet.info _("Preparing to upgrade ...")
    releases.each { |release| release.prepare }

    Puppet.notice _('Upgrading -- do not interrupt ...')
    releases.each do |release|
      installed = installed_modules[release.name]
      if installed
        release.install(Pathname.new(installed.mod.modulepath))
      else
        release.install(dir)
      end
    end

    results[:result] = :success
    results[:base_dir] = releases.first.install_dir
    results[:affected_modules] = releases
    results[:graph] = [ build_install_graph(releases.first, releases) ]

  rescue VersionAlreadyInstalledError => e
    results[:result] = (e.newer_versions.empty? ? :noop : :failure)
    results[:error] = { :oneline => e.message, :multiline => e.multiline }
  rescue => e
    results[:error] = {
      :oneline   => e.message,
      :multiline => e.respond_to?(:multiline) ? e.multiline : [e.to_s, e.backtrace].join("\n")
    }
  ensure
    results[:result] ||= :failure
  end

  results
end