Class: Mortar::Local::Python

Inherits:
Object
  • Object
show all
Includes:
InstallUtil
Defined in:
lib/mortar/local/python.rb

Constant Summary collapse

PYTHON_OSX_TGZ_NAME =
"mortar-python-osx.tgz"
PYTHON_OSX_TGZ_DEFAULT_URL_PATH =
"resource/python_osx"
PYPI_URL_PATH =
"resource/mortar_pypi"
MORTAR_PYTHON_PACKAGES =
["luigi", "mortar-luigi"]

Instance Method Summary collapse

Methods included from InstallUtil

#download_file, #ensure_mortar_local_directory, #extract_tgz, #get_resource, #gitignore_template_path, #head_resource, #http_date_to_epoch, #install_date, #install_file_for, #is_newer_version, #jython_cache_directory, #jython_directory, #local_install_directory, #local_install_directory_name, #local_log_dir, #local_project_gitignore, #local_udf_log_dir, #make_call, #make_call_sleep_seconds, #note_install, #osx?, #project_root, #render_script_template, #reset_local_logs, #run_templated_script, #unset_hadoop_env_vars, #url_date

Methods included from Helpers

#action, #ask, #confirm, #copy_if_not_present_at_dest, #default_host, #deprecate, #display, #display_header, #display_object, #display_row, #display_table, #display_with_indent, #download_to_file, #ensure_dir_exists, #error, error_with_failure, error_with_failure=, extended, extended_into, #format_bytes, #format_date, #format_with_bang, #get_terminal_environment, #home_directory, #host, #hprint, #hputs, included, included_into, #installed_with_omnibus?, #json_decode, #json_encode, #line_formatter, #longest, #output_with_bang, #quantify, #redisplay, #retry_on_exception, #running_on_a_mac?, #running_on_windows?, #set_buffer, #shell, #spinner, #status, #string_distance, #styled_array, #styled_error, #styled_hash, #styled_header, #suggestion, #test_name, #ticking, #time_ago, #truncate, #warning, #with_tty, #write_to_file

Instance Method Details

#candidatesObject



97
98
99
# File 'lib/mortar/local/python.rb', line 97

def candidates
  @candidate_pythons.dup
end

#check_or_installObject

Execute either an installation of python or an inspection of the local system to see if a usable python is available



37
38
39
40
41
42
43
44
45
# File 'lib/mortar/local/python.rb', line 37

def check_or_install
  if osx?
    # We currently only install python for osx
    install_or_update_osx
  else
    # Otherwise we check that the system supplied python will be sufficient
    check_system_python
  end
end

#check_pythons_for_virtenvObject

Inspects the list of found python installations and checks if they have virtualenv installed. The first one found will be used.



110
111
112
113
114
115
116
117
118
# File 'lib/mortar/local/python.rb', line 110

def check_pythons_for_virtenv
  @candidate_pythons.each{ |py|
    if has_virtualenv_installed(py)
      @command = py
      return true
    end
  }
  return false
end

#check_system_pythonObject

Checks if there is a usable versionpython already installed



102
103
104
105
# File 'lib/mortar/local/python.rb', line 102

def check_system_python
  @candidate_pythons = lookup_local_pythons
  return 0 != @candidate_pythons.length
end

#check_virtualenvObject



47
48
49
50
51
52
53
54
55
56
# File 'lib/mortar/local/python.rb', line 47

def check_virtualenv
  # Assumes you've already called check_or_install(), in which case
  # we can skip osx as its installation includeds virtualenv
  if osx?
    return true
  else
    return check_pythons_for_virtenv
  end

end

#desired_python_minor_versionObject



144
145
146
# File 'lib/mortar/local/python.rb', line 144

def desired_python_minor_version
  return "2.7"
end

#has_python_requirementsObject



152
153
154
# File 'lib/mortar/local/python.rb', line 152

def has_python_requirements
  return File.exists?(pip_requirements_path)
end

#has_valid_virtualenv?Boolean

Returns:

  • (Boolean)


170
171
172
173
174
175
176
177
178
179
# File 'lib/mortar/local/python.rb', line 170

def has_valid_virtualenv?
  output = `#{@command} -m virtualenv #{python_env_dir} 2>&1`
  if 0 != $?.to_i
    File.open(virtualenv_error_log_path, 'w') { |f|
      f.write(output)
    }
    return false
  end
  return true
end

#has_virtualenv_installed(python) ⇒ Object

Checks if the specified python command has virtualenv installed



122
123
124
125
126
127
128
129
# File 'lib/mortar/local/python.rb', line 122

def has_virtualenv_installed(python)
  `#{python} -m virtualenv --help 2>&1`
  if (0 != $?.to_i)
    false
  else
    true
  end
end

#install_mortar_python_package(package_name) ⇒ Object



314
315
316
317
318
319
320
# File 'lib/mortar/local/python.rb', line 314

def install_mortar_python_package(package_name)
  unless pip_install mortar_package_url(package_name)
      return false
  end
  ensure_mortar_local_directory mortar_package_dir(package_name)
  note_install mortar_package_dir(package_name)
end

#install_or_update_osxObject

Performs an installation of python specific to this project, this install includes pip and virtualenv



64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/mortar/local/python.rb', line 64

def install_or_update_osx
  @command = "#{local_install_directory}/python/bin/python"
  if should_do_python_install?
    action "Installing python to #{local_install_directory_name}" do
      install_osx
    end
  elsif should_do_update?
    action "Updating to latest python in #{local_install_directory_name}" do
      install_osx
    end
  end
  true
end

#install_osxObject



78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/mortar/local/python.rb', line 78

def install_osx
  FileUtils.mkdir_p(local_install_directory)
  python_tgz_path = File.join(local_install_directory, PYTHON_OSX_TGZ_NAME)
  download_file(python_archive_url, python_tgz_path)
  extract_tgz(python_tgz_path, local_install_directory)

  # This has been seening coming out of the tgz w/o +x so we do
  # here to be sure it has the necessary permissions
  FileUtils.chmod(0755, @command)
  File.delete(python_tgz_path)
  note_install("python")
end

#install_python_dependenciesObject



262
263
264
265
266
267
268
269
270
271
272
# File 'lib/mortar/local/python.rb', line 262

def install_python_dependencies
  action "Installing python dependencies to #{local_install_directory_name}" do
    ensure_mortar_local_directory mortar_packages_dir
    MORTAR_PYTHON_PACKAGES.each{ |package_name|
      unless install_mortar_python_package(package_name)
        return false
      end
    }
  end
  return true
end

#install_user_python_dependenciesObject



306
307
308
# File 'lib/mortar/local/python.rb', line 306

def install_user_python_dependencies
  return run_pip_command "install --requirement #{pip_requirements_path}"
end

#local_activate_pathObject



274
275
276
# File 'lib/mortar/local/python.rb', line 274

def local_activate_path
  return "#{python_env_dir}/bin/activate"
end

#local_pip_binObject



282
283
284
# File 'lib/mortar/local/python.rb', line 282

def local_pip_bin
  return "#{python_env_dir}/bin/pip"
end

#local_python_binObject



278
279
280
# File 'lib/mortar/local/python.rb', line 278

def local_python_bin
  return "#{python_env_dir}/bin/python"
end

#lookup_local_pythonsObject



131
132
133
134
135
136
137
138
139
140
141
# File 'lib/mortar/local/python.rb', line 131

def lookup_local_pythons
  # Check several python commands in decending level of desirability
  found_bins = []
  [ "python#{desired_python_minor_version}", "python" ].each{ |cmd|
    path_to_python = `which #{cmd}`.to_s.strip
    if path_to_python != ''
      found_bins << path_to_python
    end
  }
  return found_bins
end

#luigi_command_template_parameters(luigi_script, user_script_args) ⇒ Object



336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/mortar/local/python.rb', line 336

def luigi_command_template_parameters(luigi_script, user_script_args)
  script_args = [
    "--local-scheduler",
    "--logging-conf-file #{luigi_logging_config_file_path}",
    user_script_args.join(" "),
  ]
  return {
    :python_arugments => "",
    :python_script => luigi_script.executable_path(),
    :script_arguments => script_args.join(" ")
  }
end

#luigi_logging_config_file_pathObject



332
333
334
# File 'lib/mortar/local/python.rb', line 332

def luigi_logging_config_file_path
  File.expand_path("../../conf/luigi/logging.ini", __FILE__)
end

#mortar_package_dir(package) ⇒ Object



249
250
251
# File 'lib/mortar/local/python.rb', line 249

def mortar_package_dir(package)
  package_dir = "#{mortar_packages_dir}/#{package}"
end

#mortar_package_url(package) ⇒ Object



235
236
237
238
239
# File 'lib/mortar/local/python.rb', line 235

def mortar_package_url(package)
  full_host  = (host =~ /^http/) ? host : "https://api.#{host}"
  default_url = full_host + "/" + PYPI_URL_PATH
  "#{ENV.fetch('MORTAR_PACKAGE_URL', default_url)}/#{package}"
end

#mortar_packages_dirObject



245
246
247
# File 'lib/mortar/local/python.rb', line 245

def mortar_packages_dir
  return "pythonenv/mortar-packages"
end

#pip_error_log_pathObject



203
204
205
# File 'lib/mortar/local/python.rb', line 203

def pip_error_log_path
  return ENV.fetch('PIP_ERROR_LOG', "dependency_install.log")
end

#pip_install(package_url) ⇒ Object



310
311
312
# File 'lib/mortar/local/python.rb', line 310

def pip_install package_url
  return run_pip_command "install  #{package_url} --use-mirrors;"
end

#pip_requirements_pathObject



148
149
150
# File 'lib/mortar/local/python.rb', line 148

def pip_requirements_path
  return ENV.fetch('PIP_REQ_FILE', File.join(Dir.getwd, "requirements.txt"))
end

#python_archive_urlObject



164
165
166
167
168
# File 'lib/mortar/local/python.rb', line 164

def python_archive_url
  full_host  = (host =~ /^http/) ? host : "https://api.#{host}"
  default_url = full_host + "/" + PYTHON_OSX_TGZ_DEFAULT_URL_PATH
  return ENV.fetch('PYTHON_DISTRO_URL', default_url)
end

#python_command_script_template_pathObject

Path to the template which generates the bash script for running python



328
329
330
# File 'lib/mortar/local/python.rb', line 328

def python_command_script_template_path
  File.expand_path("../../templates/script/runpython.sh", __FILE__)
end

#python_directoryObject



160
161
162
# File 'lib/mortar/local/python.rb', line 160

def python_directory
  return "#{local_install_directory}/python"
end

#python_env_dirObject



156
157
158
# File 'lib/mortar/local/python.rb', line 156

def python_env_dir
  return "#{local_install_directory}/pythonenv"
end

#requirements_edit_dateObject

Date of last change to the requirements file



227
228
229
230
231
232
233
# File 'lib/mortar/local/python.rb', line 227

def requirements_edit_date
  if has_python_requirements
    return File.mtime(pip_requirements_path).to_i
  else
    return nil
  end
end

#run_luigi_script(luigi_script, user_script_args) ⇒ Object



322
323
324
325
# File 'lib/mortar/local/python.rb', line 322

def run_luigi_script(luigi_script, user_script_args)
  template_params = luigi_command_template_parameters(luigi_script, user_script_args)
  return run_templated_script(python_command_script_template_path, template_params)
end

#run_pip_command(subcmd) ⇒ Object



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/mortar/local/python.rb', line 286

def run_pip_command subcmd
  # Note that we're executing pip by passing it as a script for python to execute, this is
  # explicitly done to deal with this command breaking due to the maximum size of the path
  # to the interpreter in a shebang.  Since the containing virtualenv is already buried
  # several layers deep in the .mortar-local directory we're very likely to (read: have) hit
  # this limit.  This unfortunately leads to very vague errors about pip not existing when
  # in fact it is the truncated path to the interpreter that does not exist.  I would now
  # like the last day of my life back.
  pip_output = `. #{local_activate_path} && #{local_python_bin} #{local_pip_bin} #{subcmd}`
  if 0 != $?.to_i
    File.open(pip_error_log_path, 'w') { |f|
      f.write(pip_output)
    }
    return false
  else
    return true
  end

end

#setup_project_python_environmentObject

Creates a virtualenv in a well known location and installs any packages necessary for the users python udf



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/mortar/local/python.rb', line 183

def setup_project_python_environment
  if not has_valid_virtualenv?
    return false
  end
  if should_do_requirements_install
    action "Installing user defined python dependencies" do
      unless install_user_python_dependencies()
        return false
      end
      note_install("pythonenv")
    end
  end
  if should_install_python_dependencies?
    unless install_python_dependencies()
      return false
    end
  end
  return true
end

#should_do_python_install?Boolean

Determines if a python install needs to occur, true if no python install present or a newer version is available

Returns:

  • (Boolean)


93
94
95
# File 'lib/mortar/local/python.rb', line 93

def should_do_python_install?
  return (osx? and (not (File.exists?(python_directory))))
end

#should_do_requirements_installObject

Whether or not we need to do a ‘pip install -r requirements.txt` because we’ve never done one before or the dependencies have changed



213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/mortar/local/python.rb', line 213

def should_do_requirements_install
  if has_python_requirements
    if not install_date('pythonenv')
      # We've never done an install from requirements.txt before
      return true
    else
      return (requirements_edit_date > install_date('pythonenv'))
    end
  else
    return false
  end
end

#should_do_update?Boolean

Returns:

  • (Boolean)


58
59
60
# File 'lib/mortar/local/python.rb', line 58

def should_do_update?
  return is_newer_version('python', python_archive_url)
end

#should_install_python_dependencies?Boolean

Returns:

  • (Boolean)


253
254
255
256
257
258
259
260
# File 'lib/mortar/local/python.rb', line 253

def should_install_python_dependencies?
  MORTAR_PYTHON_PACKAGES.each{ |package|
    if update_mortar_package? package
      return true
    end
  }
  return false
end

#update_mortar_package?(package) ⇒ Boolean

Returns:

  • (Boolean)


241
242
243
# File 'lib/mortar/local/python.rb', line 241

def update_mortar_package?(package)
  return is_newer_version(mortar_package_dir(package), mortar_package_url(package))
end

#virtualenv_error_log_pathObject



207
208
209
# File 'lib/mortar/local/python.rb', line 207

def virtualenv_error_log_path
  return ENV.fetch('VE_ERROR_LOG', "virtualenv.log")
end