Class: Morpheus::Cli::Remote
- Inherits:
-
Object
- Object
- Morpheus::Cli::Remote
- Extended by:
- Term::ANSIColor
- Includes:
- CliCommand
- Defined in:
- lib/morpheus/cli/remote.rb
Constant Summary collapse
- @@appliance_config =
for caching the the contents of YAML file $home/appliances it is structured like :appliance_name => => “htt[://api.gomorpheus.com”, :active => true not named @@appliances to avoid confusion with the instance variable . This is also a command class…
nil
Instance Attribute Summary
Attributes included from CliCommand
Class Method Summary collapse
-
.active_appliance ⇒ Object
Returns two things, the remote appliance name and url.
- .appliance_config ⇒ Object
- .appliances ⇒ Object
- .appliances_file_path ⇒ Object
- .clear_active_appliance ⇒ Object
- .delete_remote(app_name) ⇒ Object
-
.load_active_remote ⇒ Object
Hash info about the active appliance.
-
.load_all_remotes(params = {}) ⇒ Array
Returns all the appliances in the configuration.
- .load_appliance_file ⇒ Object
-
.load_remote(app_name) ⇒ Hash
Info about the appliance.
- .recalculate_variable_map ⇒ Object
-
.refresh_remote(app_name) ⇒ Object
refresh_remote makes an api request to the configured appliance url and updates the appliance’s build version, status and last_check attributes.
-
.rename_remote(app_name, new_app_name) ⇒ Object
use this to rename, it update appliances file and others.
- .save_appliances(new_config) ⇒ Object
-
.save_remote(app_name, app_map) ⇒ Hash
save_remote updates the appliance info.
- .set_active_appliance(app_name) ⇒ Object
Instance Method Summary collapse
- #_check_all_appliances(options) ⇒ Object
- #_check_appliance(appliance_name, options) ⇒ Object
- #_get(appliance_name, options) ⇒ Object
- #_remove_appliance(appliance_name, options) ⇒ Object
- #add(args) ⇒ Object
- #check(args) ⇒ Object
- #check_all(args) ⇒ Object
- #connect(opts = {}) ⇒ Object
- #current(args) ⇒ Object
- #format_appliance_secure(app_map, return_color = cyan) ⇒ Object
- #format_appliance_status(app_map, return_color = cyan) ⇒ Object
- #get(args) ⇒ Object
-
#get_appliance_session_blurbs(app_map) ⇒ Object
get display info about the current and past sessions.
- #handle(args) ⇒ Object
-
#initialize ⇒ Remote
constructor
A new instance of Remote.
- #list(args) ⇒ Object
- #refresh(args) ⇒ Object
- #remove(args) ⇒ Object
- #rename(args) ⇒ Object
-
#setup(args) ⇒ Object
this is a wizard that walks through the /api/setup controller it only needs to be used once to initialize a new appliance.
-
#teardown(args) ⇒ Object
this is just for testing new appliances really it can be used.
- #unuse(args) ⇒ Object
- #update(args) ⇒ Object
- #use(args) ⇒ Object
Methods included from CliCommand
#apply_options, #build_common_options, #build_option_type_options, #build_standard_add_options, #build_standard_get_options, #build_standard_list_options, #build_standard_remove_options, #build_standard_update_options, #command_name, #default_refresh_interval, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_bytes_param, #parse_id_list, #parse_list_options, #parse_list_subtitles, #parse_payload, #parse_query_options, #print, #print_error, #println, #puts, #puts_error, #raise_command_error, #render_with_format, #run_command_for_each_arg, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!
Constructor Details
#initialize ⇒ Remote
Returns a new instance of Remote.
19 20 21 |
# File 'lib/morpheus/cli/remote.rb', line 19 def initialize() @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance end |
Class Method Details
.active_appliance ⇒ Object
Returns two things, the remote appliance name and url
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 |
# File 'lib/morpheus/cli/remote.rb', line 1413 def active_appliance if self.appliances.empty? return nil, nil end app_name, app_map = self.appliances.find {|k,v| v[:active] == true } app_url = app_map ? (app_map[:host] || app_map[:url]).to_s : nil if app_name return app_name, app_url else return nil, nil end end |
.appliance_config ⇒ Object
1408 1409 1410 |
# File 'lib/morpheus/cli/remote.rb', line 1408 def appliance_config @@appliance_config ||= load_appliance_file || {} end |
.appliances ⇒ Object
1404 1405 1406 |
# File 'lib/morpheus/cli/remote.rb', line 1404 def appliances self.appliance_config end |
.appliances_file_path ⇒ Object
1560 1561 1562 |
# File 'lib/morpheus/cli/remote.rb', line 1560 def appliances_file_path File.join(Morpheus::Cli.home_directory,"appliances") end |
.clear_active_appliance ⇒ Object
1535 1536 1537 1538 1539 1540 1541 1542 |
# File 'lib/morpheus/cli/remote.rb', line 1535 def clear_active_appliance #return set_active_appliance(nil) new_appliances = self.appliances new_appliances.each do |k,v| v.delete(:active) end save_appliances(new_appliances) end |
.delete_remote(app_name) ⇒ Object
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 |
# File 'lib/morpheus/cli/remote.rb', line 1678 def delete_remote(app_name) app_name = app_name.to_sym cur_appliances = self.appliances #.clone app_map = cur_appliances[app_name] if !app_map return nil end # remove it from config and delete credentials cur_appliances.delete(app_name) ::Morpheus::Cli::Remote.save_appliances(cur_appliances) # this should be a class method too ::Morpheus::Cli::Credentials.new(app_name, nil).clear_saved_credentials(app_name) # delete from groups too.. ::Morpheus::Cli::Groups.clear_active_group(app_name) # recalculate session variables recalculate_variable_map() # return the deleted value return app_map end |
.load_active_remote ⇒ Object
Returns Hash info about the active appliance.
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 |
# File 'lib/morpheus/cli/remote.rb', line 1489 def load_active_remote() # todo: use this in favor of Remote.active_appliance perhaps? if self.appliances.empty? return nil end result = nil app_name, app_map = self.appliances.find {|k,v| v[:active] == true } if app_map result = app_map result[:name] = app_name # app_name.to_s to be more consistant with other display values end return result end |
.load_all_remotes(params = {}) ⇒ Array
Returns all the appliances in the configuration
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 |
# File 'lib/morpheus/cli/remote.rb', line 1429 def load_all_remotes(params={}) if self.appliances.empty? return [] end all_appliances = self.appliances.collect do |app_name, app_map| row = app_map.clone # OStruct.new(app_map) tempting row[:name] = app_name row # { # active: v[:active], # name: app_name, # host: v[:host], # || v[:url], # #"LICENSE": v[:licenseIsInstalled] ? "Installed" : "(unknown)" # never return a license key from the server, ever! # status: v[:status], # username: v[:username], # last_check: v[:last_check], # last_whoami: v[:last_whoami], # last_api_request: v[:last_api_request], # last_api_result: v[:last_api_result], # last_command: v[:last_command], # last_command_result: v[:last_command_result] # } end # filter results params[:phrase] = params['phrase'] if params['phrase'] params[:name] = params['name'] if params['name'] params[:url] = params['url'] if params['url'] # params[:insecure] = params['insecure'] if params['insecure'] params[:max] = params['max'] if params['max'] params[:offset] = params['offset'] if params['offset'] params[:sort] = params['sort'] if params['sort'] params[:direction] = params['direction'] if params['direction'] if all_appliances # apply filters if params[:phrase] all_appliances = all_appliances.select do |app| app_name = app[:name] || app['name'] app_url = app[:url] || app['url'] || app[:host] app_name.to_s.include?(params[:phrase]) || app_url.to_s.include?(params[:phrase]) end end # apply sort sort_key = params[:sort] ? params[:sort].to_sym : :name if params['direction'] == 'desc' all_appliances = all_appliances.sort {|a,b| b[sort_key] <=> a[sort_key] } else all_appliances = all_appliances.sort {|a,b| a[sort_key] <=> b[sort_key] } end # limit if params[:max] all_appliances = all_appliances.first(params[:max]) end end return all_appliances end |
.load_appliance_file ⇒ Object
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 |
# File 'lib/morpheus/cli/remote.rb', line 1544 def load_appliance_file fn = appliances_file_path if File.exist? fn #Morpheus::Logging::DarkPrinter.puts "loading appliances file #{fn}" if Morpheus::Logging.debug? return YAML.load_file(fn) else return {} # return { # morpheus: { # host: 'https://api.gomorpheus.com', # active: true # } # } end end |
.load_remote(app_name) ⇒ Hash
Returns info about the appliance.
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 |
# File 'lib/morpheus/cli/remote.rb', line 1505 def load_remote(app_name) if self.appliances.empty? || app_name.nil? return nil end result = nil app_map = self.appliances[app_name.to_sym] if app_map result = app_map result[:name] = app_name # .to_s probably better end return result end |
.recalculate_variable_map ⇒ Object
1803 1804 1805 1806 1807 1808 1809 |
# File 'lib/morpheus/cli/remote.rb', line 1803 def recalculate_variable_map() Morpheus::Cli::Echo.recalculate_variable_map() # recalculate shell prompt after this change if Morpheus::Cli::Shell.has_instance? Morpheus::Cli::Shell.instance.reinitialize() end end |
.refresh_remote(app_name) ⇒ Object
refresh_remote makes an api request to the configured appliance url and updates the appliance’s build version, status and last_check attributes
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 |
# File 'lib/morpheus/cli/remote.rb', line 1700 def refresh_remote(app_name) # this might be better off staying in the CliCommands themselves # todo: public api /api/setup/check should move to /api/version or /api/server-info app_name = app_name.to_sym cur_appliances = self.appliances app_map = cur_appliances[app_name] || {} app_url = (app_map[:host] || app_map[:url]).to_s if !app_url raise "appliance config is missing url!" # should not need this end # todo: this insecure flag needs to applied everywhere now tho.. if app_map[:insecure] Morpheus::RestClient.enable_ssl_verification = false end # Morpheus::RestClient.enable_http = app_map[:insecure].to_s == 'true' setup_interface = Morpheus::SetupInterface.new({url:app_url, verify_ssl: (app_map[:insecure] != true)}) check_json_response = nil begin now = Time.now.to_i app_map[:last_check] = {} app_map[:last_check][:success] = false app_map[:last_check][:timestamp] = Time.now.to_i # todo: move /api/setup/check to /api/version or /api/server-info check_json_response = setup_interface.check() # puts "REMOTE CHECK RESPONSE:" # puts JSON.pretty_generate(check_json_response), "\n" app_map[:last_check][:http_status] = 200 app_map[:build_version] = check_json_response['buildVersion'] # || check_json_response['build_version'] #app_map[:last_check][:success] = true if check_json_response['success'] == true app_map[:status] = 'ready' app_map[:last_check][:success] = true # consider bumping this after every successful api command app_map[:last_success_at] = Time.now.to_i app_map.delete(:error) end if check_json_response['setupNeeded'] == true app_map[:setup_needed] = true app_map[:status] = 'fresh' else app_map.delete(:setup_needed) end rescue SocketError => err app_map[:status] = 'unreachable' app_map[:last_check][:http_status] = nil app_map[:last_check][:error] = err. rescue RestClient::Exceptions::Timeout => err # print_rest_exception(e, options) # exit 1 app_map[:status] = 'http-timeout' app_map[:last_check][:http_status] = nil rescue Errno::ECONNREFUSED => err app_map[:status] = 'net-error' app_map[:last_check][:error] = err. rescue OpenSSL::SSL::SSLError => err app_map[:status] = 'ssl-error' app_map[:last_check][:error] = err. rescue JSON::ParserError => err app_map[:status] = 'unrecognized' app_map[:last_check][:error] = err. rescue RestClient::Exception => err app_map[:status] = 'http-error' app_map[:http_status] = err.response ? err.response.code : nil app_map[:last_check][:error] = err. # fallback to /ping for older appliance versions (pre 2.10.5) begin Morpheus::Logging::DarkPrinter.puts "falling back to remote check via /ping ..." if Morpheus::Logging.debug? check_json_response = @setup_interface.ping() app_map[:last_check][:ping_fallback] = true app_map[:last_check][:http_status] = 200 app_map[:last_check][:success] = true app_map[:last_check][:ping_fallback] = true app_map[:build_version] = "" # unknown until whoami is executed.. app_map[:status] = 'ready' # consider bumping this after every successful api command app_map[:last_success_at] = Time.now.to_i app_map.delete(:error) rescue => ping_err Morpheus::Logging::DarkPrinter.puts "/ping failed too: #{ping_err.} ..." if Morpheus::Logging.debug? end rescue => err # should save before raising atleast..sheesh raise err app_map[:status] = 'error' app_map[:last_check][:error] = err. end # if app_map[:status] == 'ready' # app_map.delete(:error) # end # save changes to disk ... and # ... class variable returned by Remote.appliances is updated in there too... save_remote(app_name, app_map) # return the updated data return app_map, check_json_response end |
.rename_remote(app_name, new_app_name) ⇒ Object
use this to rename, it update appliances file and others. oh maybe just put this in the command handler
first check if the requested name exits and that the new name does not exist.
clone it and delete the old one. todo: switch replace symbols with strings please, makes for nicer appliances.yaml
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 |
# File 'lib/morpheus/cli/remote.rb', line 1616 def rename_remote(app_name, new_app_name) app_name = app_name.to_sym new_app_name = new_app_name.to_sym cur_appliances = self.appliances #.clone app_map = cur_appliances[app_name] if app_map.nil? print_red_alert "A remote not found by the name '#{app_name}'" #print "Did you mean one of these commands: #{suggestions.join(', ')?", reset, "\n" return nil end if cur_appliances[new_app_name] print_red_alert "A remote already exists with name '#{new_app_name}'." puts "First, you must rename or remove the existing remote." return nil end # clone the existing data # copy remote new_appliance_map = app_map.clone() new_appliance_map[:name] = new_app_name # inject name save_remote(new_app_name, new_appliance_map) # clone credentials...just overwrite keys there, f it. old_wallet = ::Morpheus::Cli::Credentials.new(app_name, nil).load_saved_credentials() if old_wallet ::Morpheus::Cli::Credentials.new(new_app_name, nil).save_credentials(new_app_name, old_wallet) #::Morpheus::Cli::Credentials.new(app_name, nil).clear_saved_credentials(app_name) end # clone groups...just overwrite keys there, f it. old_active_group = ::Morpheus::Cli::Groups.active_group(app_name) if old_active_group ::Morpheus::Cli::Groups.set_active_group(new_app_name, old_active_group) #::Morpheus::Cli::Groups.clear_active_group(app_name) end # delete stuff last # delete creds if old_wallet ::Morpheus::Cli::Credentials.new(app_name, nil).clear_saved_credentials(app_name) end # delete groups if old_active_group ::Morpheus::Cli::Groups.clear_active_group(app_name) end # delete remote delete_remote(app_name) # this is all redundant after above # # this should be a class method too # ::Morpheus::Cli::Credentials.new(app_name, nil).clear_saved_credentials(app_name) # # delete from groups too.. # ::Morpheus::Cli::Groups.clear_active_group(app_name) # # recalculate session variables # recalculate_variable_map() # return the deleted value return app_map end |
.save_appliances(new_config) ⇒ Object
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 |
# File 'lib/morpheus/cli/remote.rb', line 1564 def save_appliances(new_config) fn = appliances_file_path if !Dir.exists?(File.dirname(fn)) FileUtils.mkdir_p(File.dirname(fn)) end File.open(fn, 'w') {|f| f.write new_config.to_yaml } #Store FileUtils.chmod(0600, fn) #@@appliance_config = load_appliance_file @@appliance_config = new_config end |
.save_remote(app_name, app_map) ⇒ Hash
save_remote updates the appliance info
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 |
# File 'lib/morpheus/cli/remote.rb', line 1579 def save_remote(app_name, app_map) app_name = app_name.to_sym # it's probably better to use load_appliance_file() here instead cur_appliances = self.appliances #.clone cur_appliances[app_name] = app_map cur_appliances[app_name] ||= {:status => "unknown", :error => "Bad configuration. Missing url. See 'remote update --url'" } # this is the new set_active_appliance(), instead just pass :active => true # remove active flag from others if app_map[:active] cur_appliances.each do |k,v| is_match = (app_name ? (k == app_name) : false) if is_match v[:active] = true else v.delete(:active) # v.delete('active') # v[:active] = false end end end # persist all appliances save_appliances(cur_appliances) # recalculate session variables recalculate_variable_map() return app_map end |
.set_active_appliance(app_name) ⇒ Object
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 |
# File 'lib/morpheus/cli/remote.rb', line 1518 def set_active_appliance(app_name) app_name = app_name.to_sym new_appliances = self.appliances new_appliances.each do |k,v| is_match = (app_name ? (k == app_name) : false) if is_match v[:active] = true else v.delete(:active) # v.delete('active') # v[:active] = false end end save_appliances(new_appliances) return load_remote(app_name) end |
Instance Method Details
#_check_all_appliances(options) ⇒ Object
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 |
# File 'lib/morpheus/cli/remote.rb', line 435 def _check_all_appliances() start_time = Time.now # reresh all appliances and then display the list view id_list = ::Morpheus::Cli::Remote.appliances.keys # sort ? if id_list.size > 1 print cyan puts "Checking #{id_list.size} appliances" elsif id_list.size == 1 puts "Checking #{Morpheus::Cli::Remote.appliances.keys.first}" end id_list.each do |appliance_name| #print "." appliance, check_json_response = ::Morpheus::Cli::Remote.refresh_remote(appliance_name) end took_sec = (Time.now - start_time) print_green_success "Completed remote check of #{id_list.size} #{id_list.size == 1 ? 'appliance' : 'appliances'} in #{took_sec.round(3)}s" if [:quiet] return 0 end list([]) return 0 end |
#_check_appliance(appliance_name, options) ⇒ Object
365 366 367 368 369 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 402 403 404 405 406 407 408 409 410 411 412 413 |
# File 'lib/morpheus/cli/remote.rb', line 365 def _check_appliance(appliance_name, ) exit_code, err = 0, nil begin appliance = nil if appliance_name == "current" appliance = ::Morpheus::Cli::Remote.load_active_remote() if !appliance raise_command_error "No current appliance, see `remote use`." end appliance_name = appliance[:name] else appliance = ::Morpheus::Cli::Remote.load_remote(appliance_name) if !appliance raise_command_error "Remote not found by the name '#{appliance_name}'" end end # found appliance, now refresh it start_time = Time.now # print cyan # print "Checking remote url: #{appliance[:host]} ..." appliance, check_json_response = ::Morpheus::Cli::Remote.refresh_remote(appliance_name) took_sec = (Time.now - start_time) exit_code = (appliance[:status] == 'ready' || appliance[:status] == 'fresh') ? 0 : 1 if exit_code == 0 if appliance[:error] exit_code = 1 err = "Check Failed: #{appliance[:error]}" end end render_result = render_with_format(check_json_response, ) return exit_code if render_result print_green_success "Completed remote check of #{appliance_name} in #{took_sec.round(3)}s" return _get(appliance[:name], {}) rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#_get(appliance_name, options) ⇒ Object
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 |
# File 'lib/morpheus/cli/remote.rb', line 610 def _get(appliance_name, ) exit_code, err = 0, nil begin appliance = nil if appliance_name == "current" appliance = ::Morpheus::Cli::Remote.load_active_remote() if !appliance err = "No current appliance, see `remote use`." exit_code = 1 end appliance_name = appliance[:name] else appliance = ::Morpheus::Cli::Remote.load_remote(appliance_name) if !appliance err = "Remote appliance not found by the name '#{appliance_name}'" exit_code = 1 end end if [:quiet] return exit_code, err end if [:json] json_response = {'appliance' => appliance} # mock payload puts as_json(json_response, , "appliance") return exit_code, err end if [:yaml] json_response = {'appliance' => appliance} # mock payload puts as_yaml(json_response, , "appliance") return exit_code, err end if [:url_only] if appliance print cyan, (appliance[:url] || appliance[:host]),"\n",reset return exit_code, err else print_error red, err,"\n",reset return exit_code, err end end if exit_code != 0 print_error red, err,"\n",reset return exit_code, err end if appliance[:active] # print_h1 "Current Remote Appliance: #{appliance[:name]}" print_h1 "Morpheus Appliance", [], else print_h1 "Morpheus Appliance", [], end print cyan description_cols = { "Name" => :name, "URL" => :host, "Secure" => lambda {|it| format_appliance_secure(it) }, "Version" => lambda {|it| it[:build_version] ? "#{it[:build_version]}" : 'unknown' }, "Status" => lambda {|it| format_appliance_status(it, cyan) }, "Username" => :username, # "Authenticated" => lambda {|it| format_boolean it[:authenticated] }, # todo: fix this layout, obv "Activity" => lambda {|it| get_appliance_session_blurbs(it).join("\n" + (' '*10)) } } print cyan puts as_description_list(appliance, description_cols) # if appliance[:insecure] # puts " Ignore SSL Errors: Yes" # else # puts " Ignore SSL Errors: No" # end if appliance[:active] # print cyan print cyan, "# => #{appliance[:name]} is the current remote appliance.", reset, "\n\n" end return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#_remove_appliance(appliance_name, options) ⇒ Object
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 |
# File 'lib/morpheus/cli/remote.rb', line 727 def _remove_appliance(appliance_name, ) appliance_name = appliance_name.to_sym appliance = ::Morpheus::Cli::Remote.load_remote(appliance_name) if !appliance raise_command_error "Remote appliance not found by the name '#{appliance_name}'" end appliances = ::Morpheus::Cli::Remote.appliances if appliances[appliance_name].nil? if [:quiet] return 1 end print_red_alert "Remote does not exist with name '#{appliance_name.to_s}'" return 1 end # ok, delete it ::Morpheus::Cli::Remote.delete_remote(appliance_name) # return result if [:quiet] return 0 end print_green_success "Deleted remote #{appliance_name}" # list([]) return 0 end |
#add(args) ⇒ Object
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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 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 |
# File 'lib/morpheus/cli/remote.rb', line 107 def add(args) exit_code, err = 0, nil = {} params = {} new_appliance_map = {} use_it = false secure = nil optparse = Morpheus::Cli::OptionParser.new do|opts| = subcommand_usage("[name] [url]") = <<-EOT [name] The name for your appliance. eg. mymorph [url] The url of your appliance eg. https://demo.mymorpheus.com EOT opts. = + "\n" + opts.on(nil, '--use', "Make this the current appliance" ) do use_it = true new_appliance_map[:active] = true end # let's free up the -d switch for global options, maybe? opts.on( '-d', '--default', "Does the same thing as --use" ) do use_it = true new_appliance_map[:active] = true end opts.on(nil, "--secure", "Prevent insecure HTTPS communication. This is enabled by default.") do secure = true end opts.on(nil, "--insecure", "Allow insecure HTTPS communication. i.e. Ignore SSL errors.") do secure = false end (opts, , [:options, :quiet]) opts. = <<-EOT This will add a new remote appliance to your morpheus client configuration. If this is your first remote, --use is automatically applied so it will become the current remote appliance. This command will prompt you to login and/or setup a fresh appliance. To skip login/setup, use the --quiet option. EOT end optparse.parse!(args) if args.count > 2 raise_command_error "wrong number of arguments, expected 0-2 and got (#{args.count}) #{args.join(' ')}\n#{optparse}" end # load current appliances appliances = ::Morpheus::Cli::Remote.appliances # always use the first one if appliances.empty? new_appliance_map[:active] = true end new_appliance_name = args[0] if args[0] url = args[1] if args[1] # Name still_prompting = true while still_prompting do if new_appliance_name.to_s.empty? v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true, 'description' => 'A unique name for the remote Morpheus appliance. Example: local'}], [:options]) new_appliance_name = v_prompt['name'] end # for the sake of sanity if [:current, :all].include?(new_appliance_name.to_sym) raise_command_error "The specified appliance name '#{new_appliance_name}' is invalid." new_appliance_name = nil end # unique name existing_appliance = appliances[new_appliance_name.to_sym] if existing_appliance print_error red,"The specified appliance name '#{new_appliance_name}' already exists with the URL #{existing_appliance[:url] || existing_appliance[:host]}",reset,"\n" new_appliance_name = nil end if new_appliance_name.to_s.empty? if [:no_prompt] return 1 end still_prompting = true else still_prompting = false end end new_appliance_map[:name] = new_appliance_name.to_sym # URL still_prompting = true while still_prompting do if !url v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'url', 'fieldLabel' => 'URL', 'type' => 'text', 'required' => true, 'description' => 'The URL of the remote Morpheus appliance. Example: https://10.0.2.2'}], [:options]) url = v_prompt['url'] end if url !~ /^https?\:\/\/.+/ print_error red,"The specified appliance url '#{url}' is invalid.",reset,"\n" still_prompting = true url = nil else still_prompting = false end end # let's replace :host with :url new_appliance_map[:host] = url new_appliance_map[:url] = url # Insecure? if url.include?('https:') && secure.nil? # This is kind of annoying to always see, just default to true, use --insecure if you need to. #v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'secure', 'fieldLabel' => 'Secure', 'type' => 'checkbox', 'required' => false, 'defaultValue' => true, 'description' => 'Prevent insecure HTTPS communication. This is enabled by default.'}], options[:options]) #secure = v_prompt['secure'].to_s == 'true' || v_prompt['secure'].to_s == 'on' end if secure == false new_appliance_map[:insecure] = true end # save it appliance = ::Morpheus::Cli::Remote.save_remote(new_appliance_name.to_sym, new_appliance_map) if ![:quiet] # print_green_success "Added remote #{new_appliance_name}" print_green_success "Added remote #{new_appliance_name}" end # hit check api and store version and other info if ![:quiet] print cyan puts "Inspecting remote appliance #{appliance[:host]} ..." end appliance, check_json_response = ::Morpheus::Cli::Remote.refresh_remote(new_appliance_name.to_sym) if ![:quiet] print cyan puts "Status is: #{format_appliance_status(appliance)}" end # puts "refreshed appliance #{appliance.inspect}" # determine command exit_code and err exit_code = (appliance[:status] == 'ready' || appliance[:status] == 'fresh') ? 0 : 1 if exit_code == 0 if appliance[:error] exit_code = 1 err = "Check Failed: #{appliance[:error]}" end end if [:quiet] return exit_code, err end if [:json] puts as_json(check_json_response, ) return exit_code, err end # just skip setup/login stuff is no prompt -N is used. if [:no_prompt] return exit_code, err end # check_cmd_result = check_appliance([new_appliance_name, "--quiet"]) # check_cmd_result = check_appliance([new_appliance_name]) if appliance[:status] == 'fresh' # || appliance[:setup_needed] == true if !appliance[:active] if ::Morpheus::Cli::OptionTypes::confirm("Would you like to switch to using this remote now?", .merge({default: true})) use([appliance[:name]]) appliance[:active] = true # just in case, could reload instead with load_active_remote() end end print cyan puts "It looks like this appliance needs to be setup. Starting setup ..." return setup([new_appliance_name]) # no need to login, setup() handles that end # only login if you are using this remote # maybe remote use should do the login prompting eh? # if appliance[:active] && appliance[:status] == 'ready' if appliance[:status] == 'ready' print reset if ::Morpheus::Cli::OptionTypes::confirm("Would you like to login now?", .merge({default: true})) login_result = ::Morpheus::Cli::Login.new.handle(["--remote", appliance[:name].to_s]) = true if login_result == 0 = false end while do if ::Morpheus::Cli::OptionTypes::confirm("Login was unsuccessful. Would you like to try again?", .merge({default: true})) login_result = ::Morpheus::Cli::Login.new.handle(["--remote", appliance[:name].to_s]) if login_result == 0 = false end else = false end end end if !appliance[:active] if ::Morpheus::Cli::OptionTypes::confirm("Would you like to switch to using this remote now?", .merge({default: true})) use([appliance[:name]]) end end else #puts "Status is #{format_appliance_status(appliance)}" end # print new appliance details _get(appliance[:name], {}) return exit_code, err end |
#check(args) ⇒ Object
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 |
# File 'lib/morpheus/cli/remote.rb', line 331 def check(args) = {} checkall = false optparse = Morpheus::Cli::OptionParser.new do|opts| opts. = subcommand_usage("[name]") (opts, , [:json, :yaml, :csv, :fields, :quiet, :dry_run, :remote]) opts.on('-a', '--all', "Check all remotes.") do checkall = true end opts. = <<-EOT Check the status of a remote appliance. [name] is optional. This is the name of a remote. Default is the current remote. Can be passed as 'all'. to perform remote check-all. This makes a request to the configured appliance url and updates the status and version. EOT end optparse.parse!(args) if checkall == true return _check_all_appliances() end if args.count == 0 id_list = ['current'] else id_list = parse_id_list(args) end # trick for remote check all if id_list.length == 1 && id_list[0].to_s.downcase == 'all' return _check_all_appliances() end #connect(options) return run_command_for_each_arg(id_list) do |arg| _check_appliance(arg, ) end end |
#check_all(args) ⇒ Object
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 |
# File 'lib/morpheus/cli/remote.rb', line 415 def check_all(args) = {} checkall = false optparse = Morpheus::Cli::OptionParser.new do|opts| opts. = subcommand_usage() (opts, , [:quiet]) opts. = <<-EOT Refresh all remote appliances. This makes a request to each of the configured appliance urls and updates the status and version. EOT end optparse.parse!(args) if args.count != 0 raise_command_error "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}" end connect() # needed? _check_all_appliances() end |
#connect(opts = {}) ⇒ Object
23 24 25 26 27 |
# File 'lib/morpheus/cli/remote.rb', line 23 def connect(opts={}) connect_opts = {:skip_verify_access_token => true}.merge(opts) @api_client = establish_remote_appliance_connection(connect_opts) @setup_interface = @api_client.setup end |
#current(args) ⇒ Object
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 |
# File 'lib/morpheus/cli/remote.rb', line 827 def current(args) = {} name_only = false url_only = false optparse = Morpheus::Cli::OptionParser.new do|opts| opts. = subcommand_usage() opts.on( '-n', '--name', "Print only the name." ) do name_only = true end opts.on( '-u', '--url', "Print only the url." ) do url_only = true end (opts, , []) opts. = "Print details about the current remote appliance." + "The default behavior is the same as 'remote get current'." end optparse.parse!(args) if args.count != 0 raise_command_error "wrong number of arguments, expected 0 and got (#{args.count}) #{args.join(' ')}\n#{optparse}" end connect() # if !@appliance_name # print yellow, "No current appliance, see `remote use`\n", reset # return 1 # end #connect(options) if name_only print cyan, @appliance_name,"\n",reset return 0 elsif url_only print cyan, @appliance_url,"\n",reset return 0 else return _get("current", ) end end |
#format_appliance_secure(app_map, return_color = cyan) ⇒ Object
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 |
# File 'lib/morpheus/cli/remote.rb', line 1322 def format_appliance_secure(app_map, return_color=cyan) return "" if !app_map out = "" app_url = (app_map[:host] || app_map[:url]).to_s is_ssl = app_url =~ /^https/ if !is_ssl out << "No (no SSL)" else if app_map[:insecure] out << "No (Ignore SSL Errors)" else # should have a flag that gets set when everything actually looks good.. out << "Yes" end end out end |
#format_appliance_status(app_map, return_color = cyan) ⇒ Object
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 |
# File 'lib/morpheus/cli/remote.rb', line 1299 def format_appliance_status(app_map, return_color=cyan) return "" if !app_map status_str = app_map[:status] || app_map['status'] || "unknown" # get_object_value(app_map, :status) status_str = status_str.empty? ? "unknown" : status_str.to_s.downcase out = "" if status_str == "new" out << "#{cyan}#{status_str.upcase}#{return_color}" elsif status_str == "fresh" # maybe just green instead? out << "#{magenta}#{status_str.upcase}#{return_color}" elsif status_str == "ready" out << "#{green}#{status_str.upcase}#{return_color}" elsif status_str == "http-error" out << "#{red}HTTP ERROR#{return_color}" elsif ['error', 'net-error', 'ssl-error', 'http-timeout', 'unreachable', 'unrecognized'].include?(status_str) out << "#{red}#{status_str.gsub('-', ' ').upcase}#{return_color}" else # dunno out << "#{yellow}#{status_str.upcase}#{return_color}" end out end |
#get(args) ⇒ Object
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 |
# File 'lib/morpheus/cli/remote.rb', line 587 def get(args) = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[name]") opts.on( '-u', '--url', "Print only the url." ) do [:url_only] = true end (opts, , [:json,:csv, :fields, :quiet]) end optparse.parse!(args) if args.count < 1 print_error Morpheus::Terminal.angry_prompt puts_error "#{command_name} get expects argument [name]." puts_error optparse return 1 end #connect(options) id_list = parse_id_list(args) return run_command_for_each_arg(id_list) do |arg| _get(arg, ) end end |
#get_appliance_session_blurbs(app_map) ⇒ Object
get display info about the current and past sessions
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 |
# File 'lib/morpheus/cli/remote.rb', line 1342 def get_appliance_session_blurbs(app_map) # app_map = OStruct.new(app_map) blurbs = [] # Current User # username = app_map[:username] if app_map[:status] == 'ready' if app_map[:authenticated] #blurbs << app_map[:username] ? "Authenticated as #{app_map[:username]}" : "Authenticated" blurbs << "Authenticated." if app_map[:last_login_at] blurbs << "Logged in #{format_duration(app_map[:last_login_at])} ago." end else if app_map[:last_logout_at] blurbs << "Logged out #{format_duration(app_map[:last_logout_at])} ago." else blurbs << "Logged out." end if app_map[:last_login_at] blurbs << "Last login at #{format_local_dt(app_map[:last_login_at])}." end end if app_map[:last_success_at] blurbs << "Last success at #{format_local_dt(app_map[:last_success_at])}" end else if app_map[:last_check] if app_map[:last_check][:timestamp] blurbs << "Last checked #{format_duration(app_map[:last_check][:timestamp])} ago." end if app_map[:last_check][:error] last_error_msg = truncate_string(app_map[:last_check][:error], 250) blurbs << "Error: #{last_error_msg}" end if app_map[:last_check][:http_status] blurbs << "HTTP #{app_map[:last_check][:http_status]}" end end if app_map[:last_success_at] blurbs << "Last Success: #{format_local_dt(app_map[:last_success_at])}" end end return blurbs end |
#handle(args) ⇒ Object
29 30 31 |
# File 'lib/morpheus/cli/remote.rb', line 29 def handle(args) handle_subcommand(args) end |
#list(args) ⇒ Object
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 |
# File 'lib/morpheus/cli/remote.rb', line 33 def list(args) = {} params = {} show_all_activity = false optparse = Morpheus::Cli::OptionParser.new do|opts| opts. = subcommand_usage() opts.on("-a",'--all', "Show all the appliance activity details") do show_all_activity = true end (opts, , [:list, :json, :yaml, :csv, :fields]) opts. = <<-EOT This outputs a list of the configured remote appliances. It also indicates the current appliance. The current appliance is where morpheus will send its commands by default. That is, in absence of the '--remote' option. EOT end optparse.parse!(args) if args.count > 0 raise_command_error "wrong number of arguments, expected 0 and got (#{args.count}) #{args.join(' ')}\n#{optparse}" end #connect(options) params.merge!(()) appliances = ::Morpheus::Cli::Remote.load_all_remotes(params) # if appliances.empty? # raise_command_error "You have no appliances configured. See the `remote add` command." # end json_response = {"appliances" => appliances} if [:json] puts as_json(json_response, , "appliances") return 0 elsif [:yaml] puts as_yaml(json_response, , "appliances") return 0 elsif [:csv] puts records_as_csv(appliances, ) return 0 end if appliances.empty? if params[:phrase] print cyan,"0 remotes matched '#{params[:phrase]}'", reset, "\n" else print yellow,"You have no appliances configured. See the `remote add` command.", reset, "\n" end else title = "Morpheus Appliances" subtitles = parse_list_subtitles() print_h1 title, subtitles, print cyan columns = [ {:active => {:display_name => "", :display_method => lambda {|it| it[:active] ? "=>" : "" } } }, # {:name => {display_method: lambda {|it| it[:active] ? "#{green}#{it[:name]}#{reset}#{cyan}" : it[:name] }, :width => 16 } }, {:name => {display_method: lambda {|it| it[:name] } } }, {:url => {display_method: lambda {|it| it[:host] || it[:url] }, :width => 40 } }, {:version => lambda {|it| it[:build_version] } }, {:status => lambda {|it| format_appliance_status(it, cyan) } }, :username, # {:session => {display_method: lambda {|it| get_appliance_session_blurbs(it).join(' ') }, max_width: 24} } {:activity => {display_method: lambda {|it| show_all_activity ? get_appliance_session_blurbs(it).join("\t") : get_appliance_session_blurbs(it).first } } } ] print as_pretty_table(appliances, columns, ) print reset if @appliance_name #unless appliances.keys.size == 1 print cyan, "\n# => #{@appliance_name} is the current remote appliance\n", reset #end else print cyan, "\n# => No current remote appliance, see `remote use`\n", reset end print reset, "\n" end return 0, nil end |
#refresh(args) ⇒ Object
327 328 329 |
# File 'lib/morpheus/cli/remote.rb', line 327 def refresh(args) check_appliance(args) end |
#remove(args) ⇒ Object
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 |
# File 'lib/morpheus/cli/remote.rb', line 701 def remove(args) = {} optparse = Morpheus::Cli::OptionParser.new do|opts| opts. = subcommand_usage("[name]") (opts, , [:auto_confirm, :quiet]) opts. = <<-EOT This will delete the specified remote appliance(s) from your local configuration. [name] is required. This is the name of a remote. More than one can be passed. EOT end optparse.parse!(args) if args.count == 0 #id_list = ['current'] raise_command_error "wrong number of arguments, expected 1-N and got 0\n#{optparse}" else id_list = parse_id_list(args) end #connect(options) unless [:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to delete #{id_list.size == 1 ? 'remote' : 'remotes'}: #{anded_list(id_list)}?", ) return 9, "aborted command" end return run_command_for_each_arg(id_list) do |arg| _remove_appliance(arg, ) end end |
#rename(args) ⇒ Object
459 460 461 462 463 464 465 466 467 468 469 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 |
# File 'lib/morpheus/cli/remote.rb', line 459 def rename(args) = {} params = {} use_it = false is_insecure = nil new_name = nil optparse = Morpheus::Cli::OptionParser.new do|opts| opts. = subcommand_usage("[name] [new name]") opts.on(nil, "--name NAME", "Update the name of your remote appliance") do |val| new_name = val end # opts.on(nil, '--use', "Make this the current appliance" ) do # use_it = true # params[:active] = true # end (opts, , [:auto_confirm, :quiet]) opts. = <<-EOT Rename a remote. This changes your client configuration remote name, not the appliance itself. [name] is required. This is the current name of a remote. [new name] is required. This is the new name for the remote. This must not already be in use. EOT end optparse.parse!(args) if args.count != 2 print_error Morpheus::Terminal.angry_prompt puts_error "#{command_name} rename expects argument [name]." puts_error optparse return 1 end appliance_name = args[0].to_sym new_appliance_name = args[1].to_sym appliance = ::Morpheus::Cli::Remote.load_remote(appliance_name) if !appliance raise_command_error "Remote appliance not found by the name '#{appliance_name}'" end # don't allow overwrite yet matching_appliance = ::Morpheus::Cli::Remote.load_remote(new_appliance_name) if matching_appliance raise_command_error "Remote appliance already exists with the name '#{new_appliance_name}'" end unless [:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to rename #{appliance_name} to #{new_appliance_name}?", ) return 9, "aborted command" end # this does all the work ::Morpheus::Cli::Remote.rename_remote(appliance_name, new_appliance_name) print_green_success "Renamed remote #{appliance_name} to #{new_appliance_name}" # todo: just go ahead and refresh it now... # _check(appliance_name, {:quiet => true}) # appliance, check_json_response = ::Morpheus::Cli::Remote.refresh_remote(new_appliance_name) # print new appliance details _get(new_appliance_name, {}) return 0, nil end |
#setup(args) ⇒ Object
this is a wizard that walks through the /api/setup controller it only needs to be used once to initialize a new appliance
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 |
# File 'lib/morpheus/cli/remote.rb', line 868 def setup(args) = {} optparse = Morpheus::Cli::OptionParser.new do|opts| opts. = subcommand_usage() (opts, , [:payload, :options, :json, :dry_run, :quiet, :remote]) opts.on('--hubmode MODE','--hubmode MODE', "Choose an option for hub registration possible values are login, register, skip.") do |val| [:hubmode] = val.to_s.downcase end opts. = "Initialize a fresh appliance.\n" + "You will be prompted to create the master tenant and admin user.\n" + "If Morpheus Hub registration is enabled, you may login or register to retrieve a license key.\n" + "Setup is only available on a new, freshly installed, remote appliance\n" + "and it may only be used successfully once." end optparse.parse!(args) # first arg as remote name otherwise the active appliance is connected to if args.count > 1 raise_command_error "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}" end if args[0] [:remote] = args[0] end connect() if !@appliance_name print yellow, "No active appliance, see `remote use`\n", reset return false end # construct payload payload = nil if [:payload] payload = [:payload] else params = {} params.deep_merge!([:options].reject {|k,v| k.is_a?(Symbol) }) if [:options] # this works without any authentication! # it will allow anyone to use it, if there are no users/accounts in the system. #@api_client = establish_remote_appliance_connection(options) @setup_interface = @api_client.setup #use me # @setup_interface = Morpheus::SetupInterface.new({url:@appliance_url,access_token:@access_token}) appliance_status_json = nil begin appliance_status_json = @setup_interface.get() if appliance_status_json['success'] != true print_error red, "Setup not available for appliance #{@appliance_name} - #{@appliance_url}.\n", reset print_error red, "#{appliance_status_json['msg']}\n", reset return false end rescue RestClient::Exception => e print_rest_exception(e, ) return false end # retrieved hub.enabled and hub.url hub_settings = appliance_status_json['hubSettings'] || appliance_status_json['hub'] || {} # store login/registration info in here, for prompt default values hub_info = nil print cyan print_h2 "Remote Setup: #{@appliance_name} - #{@appliance_url}" print cyan puts "Welcome to the setup of your new Morpheus Appliance #{@appliance_name} @ #{@appliance_url}" puts "It looks like you're the first here, so let's begin." hubmode = nil hub_init_payload = nil # gets included as payload for hub scoped like hub.email if hub_settings['enabled'] # Hub Registration hub_action_dropdown = [ {'name' => 'Login to existing hub account', 'value' => 'login', 'isDefault' => true}, {'name' => 'Register a new hub account', 'value' => 'register'}, {'name' => 'Skip this step and manually install a license later.', 'value' => 'skip'}, {'name' => 'Abort', 'value' => 'abort'} ] print cyan puts "Morpheus Hub registration is enabled for your appliance." puts "This step will connect to the Morpheus Hub at #{hub_settings['url']}" puts "This is done to retrieve and install the license key for your appliance." puts "You have several options for how to proceed:" hub_action_dropdown.each_with_index do |hub_action, idx| puts "#{idx+1}. #{hub_action['name']} [#{hub_action['value']}]" end print "\n", reset while hubmode == nil do [:options]['hubmode'] = [:hubmode] if .key?(:hubmode) v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'hubmode', 'fieldLabel' => 'Choose Hub Mode', 'type' => 'select', 'selectOptions' => hub_action_dropdown, 'required' => true, 'defaultValue' => 'login'}], [:options]) hubmode = v_prompt['hubmode'] if hubmode == 'login' # print cyan # puts "MORPHEUS HUB #{hub_settings['url']}" # puts "The Command Center for DevOps" # print reset # Hub Login print_h2 "Morpheus Hub Login @ #{hub_settings['url']}", hub_login_option_types = [ {'fieldContext' => 'hub', 'fieldName' => 'email', 'fieldLabel' => 'Email', 'type' => 'text', 'required' => true, 'description' => 'Email Address of existing Morpheus Hub user to link with.'}, {'fieldContext' => 'hub', 'fieldName' => 'password', 'fieldLabel' => 'Password', 'type' => 'password', 'required' => true, 'description' => 'Password of existing Morpheus Hub user.'}, ] v_prompt = Morpheus::Cli::OptionTypes.prompt(hub_login_option_types, [:options]) hub_login_payload = v_prompt['hub'] hub_login_response = nil begin hub_login_response = @setup_interface.hub_login(hub_login_payload) hub_init_payload = hub_login_payload hub_info = {'email' => hub_login_payload['email'], 'password' => hub_login_payload['password'] } hub_info.deep_merge!(hub_login_response['data']['info']) if (hub_login_response['data'] && hub_login_response['data']['info']) hub_info.deep_merge!(hub_login_response['hub']) if hub_login_response['hub'].is_a?(Hash) print_green_success "Logged into Morpheus Hub as #{hub_info['email']}" rescue RestClient::Exception => e hub_login_response = parse_rest_exception(e) error_msg = hub_login_response["msg"] || "Hub login failed." print_error red,error_msg,reset,"\n" hubmode = nil #print_rest_exception(e, options) #exit 1 end # DEBUG if [:debug] && hub_login_response print_h2 "JSON response for hub login" Morpheus::Logging::DarkPrinter.puts as_json(hub_login_response) end elsif hubmode == 'register' # Hub Registration print_h2 "Morpheus Hub Registration", hub_register_option_types = [ {'fieldContext' => 'hub', 'fieldName' => 'companyName', 'fieldLabel' => 'Company Name', 'type' => 'text', 'required' => true, 'description' => 'Company Name of new Morpheus Hub account to be created.'}, {'fieldContext' => 'hub', 'fieldName' => 'firstName', 'fieldLabel' => 'First Name', 'type' => 'text', 'required' => true, 'description' => 'First Name of new Morpheus Hub user.'}, {'fieldContext' => 'hub', 'fieldName' => 'lastName', 'fieldLabel' => 'Last Name', 'type' => 'text', 'required' => true, 'description' => 'Last Name of new Morpheus Hub user.'}, {'fieldContext' => 'hub', 'fieldName' => 'email', 'fieldLabel' => 'Email', 'type' => 'text', 'required' => true, 'description' => 'Email Address of new Morpheus Hub user.'} ] v_prompt = Morpheus::Cli::OptionTypes.prompt(hub_register_option_types, [:options]) hub_register_payload = v_prompt['hub'] # Password prompt with re-prompting if no match need_password = true if [:no_prompt] if [:options]['hub'] && [:options]['hub']['password'] [:options]['hub']['confirmPassword'] = [:options]['hub']['password'] end end while need_password do password_option_types = [ {'fieldContext' => 'hub', 'fieldName' => 'password', 'fieldLabel' => 'Create Password', 'type' => 'password', 'required' => true, 'description' => 'Confirm password of new Morpheus Hub user.'}, {'fieldContext' => 'hub', 'fieldName' => 'confirmPassword', 'fieldLabel' => 'Confirm Password', 'type' => 'password', 'required' => true, 'description' => 'Confirm password of new Morpheus Hub user.'} ] v_prompt = Morpheus::Cli::OptionTypes.prompt(password_option_types, [:options]) if v_prompt['hub']['password'] == v_prompt['hub']['confirmPassword'] hub_register_payload.deep_merge!(v_prompt['hub']) need_password = false else print_error red, "Password confirmation does not match. Re-enter your new password.", reset, "\n" end end begin hub_register_response = @setup_interface.hub_register(hub_register_payload) hub_init_payload = hub_register_payload hub_info = {'email' => hub_register_payload['email'], 'password' => hub_register_payload['password'] } hub_info.deep_merge!(hub_register_payload) hub_info.deep_merge!(hub_register_response['data']['info']) if (hub_register_response['data'] && hub_register_response['data']['info']) hub_info.deep_merge!(hub_register_response['hub']) if hub_register_response['hub'].is_a?(Hash) print_green_success "Registered with Morpheus Hub as #{hub_info['email']}" # uh ok so that means the init() request can use login # this avoid duplicate email error # but it can also just omit hubMode from the init() payload to achieve the same thing. # hubmode = nil rescue RestClient::Exception => e hub_register_response = parse_rest_exception(e) error_msg = hub_register_response["msg"] || "Hub Registration failed." print_error red,error_msg,reset,"\n" hubmode = nil #print_rest_exception(e, options) #exit 1 end # DEBUG if [:debug] && hub_register_response print_h2 "JSON response for hub registration" Morpheus::Logging::DarkPrinter.puts as_json(hub_register_response) end elsif hubmode == 'skip' print cyan,"Skipping hub registraton for now...",reset,"\n" # puts "You may enter a license key later." elsif hubmode == 'abort' return 9, "aborted command" else hubmode = nil end end end # ok, we're done with the hub. # now build the payload for POST /api/setup/init payload = {} payload.deep_merge!(params) # print cyan #print_h1 "Morpheus Appliance Setup", [], options #print cyan #puts "Initializing remote appliance at URL: #{@appliance_url}" # Master Account print_h2 "Create Master Tenant", account_option_types = [ {'fieldName' => 'accountName', 'fieldLabel' => 'Master Tenant Name', 'type' => 'text', 'required' => true, 'defaultValue' => (hub_info ? hub_info['companyName'] : nil), 'description' => 'A unique name for the Master Tenant (account).'}, ] v_prompt = Morpheus::Cli::OptionTypes.prompt(account_option_types, [:options]) payload.merge!(v_prompt) # Master User print_h2 "Create Master User", user_option_types = [ {'fieldName' => 'firstName', 'fieldLabel' => 'First Name', 'type' => 'text', 'required' => false, 'defaultValue' => (hub_info ? hub_info['firstName'] : nil), 'description' => 'First name of the user.'}, {'fieldName' => 'lastName', 'fieldLabel' => 'Last Name', 'type' => 'text', 'required' => false, 'defaultValue' => (hub_info ? hub_info['lastName'] : nil), 'description' => 'Last name of the user.'}, {'fieldName' => 'email', 'fieldLabel' => 'Email', 'type' => 'text', 'required' => true, 'defaultValue' => (hub_info ? hub_info['email'] : nil), 'description' => 'A unique email address for the user.'}, {'fieldName' => 'username', 'fieldLabel' => 'Username', 'type' => 'text', 'required' => true, 'description' => 'A unique username for the master user.'} ] v_prompt = Morpheus::Cli::OptionTypes.prompt(user_option_types, [:options]) payload.merge!(v_prompt) # Password prompt with re-prompting if no match need_password = true if [:no_prompt] [:options]['confirmPassword'] = payload['password'] payload['confirmPassword'] = payload['password'] if payload['password'] end while need_password do password_option_types = [ {'fieldName' => 'password', 'fieldLabel' => 'Create Password', 'type' => 'password', 'required' => true, 'description' => 'Create a new password for the user.'}, {'fieldName' => 'confirmPassword', 'fieldLabel' => 'Confirm Password', 'type' => 'password', 'required' => true, 'description' => 'Confirm the new password for the user.'}, ] password_prompt = Morpheus::Cli::OptionTypes.prompt(password_option_types, [:options]) if password_prompt['password'] == password_prompt['confirmPassword'] payload['password'] = password_prompt['password'] need_password = false else print_error red, "Password confirmation does not match. Re-enter your new password.", reset, "\n" end end # Appliance Settings default_appliance_url = appliance_status_json['applianceUrl'] if default_appliance_url && default_appliance_url.include?('10.0.2.2:8080') # ignore this default value. default_appliance_url = @appliance_url end default_appliance_name = appliance_status_json['applianceName'] if default_appliance_name.nil? default_appliance_name = @appliance_name end print_h2 "Initial Setup", extra_option_types = [ {'fieldName' => 'applianceName', 'fieldLabel' => 'Appliance Name', 'type' => 'text', 'required' => true, 'defaultValue' => default_appliance_name, 'description' => 'A name for identifying your morpheus appliance.'}, {'fieldName' => 'applianceUrl', 'fieldLabel' => 'Appliance URL', 'type' => 'text', 'required' => true, 'defaultValue' => default_appliance_url, 'description' => 'Appliance URL. Can be used for integrations and callbacks.'}, {'fieldName' => 'backups', 'fieldLabel' => 'Enable Backups', 'type' => 'checkbox', 'required' => false, 'defaultValue' => 'off', 'description' => 'Backups. Default is off. This means backups are created automatically during provisioning.'}, {'fieldName' => 'monitoring', 'fieldLabel' => 'Enable Monitoring', 'type' => 'checkbox', 'required' => false, 'defaultValue' => 'on', 'description' => 'Enable Monitoring. This means checks are created automatically during provisioning.'}, {'fieldName' => 'logs', 'fieldLabel' => 'Enable Logs', 'type' => 'checkbox', 'required' => false, 'defaultValue' => 'on', 'description' => 'Enable Logs. This means container logs are collected.'} ] v_prompt = Morpheus::Cli::OptionTypes.prompt(extra_option_types, [:options]) payload.merge!(v_prompt) # include hubmode and hub params for login or registration # actually we remove hubMode because it has already been setup, probably just now, # and the init() request will just used the same creds instead of # reauthenticated/registering with the hub if hubmode payload['hubMode'] = hubmode end if hub_init_payload payload['hub'] = hub_init_payload end if hubmode == 'register' || hubmode == 'login' payload.delete('hubMode') payload.delete('hub') end end # ok, make the api request @setup_interface.setopts() if [:dry_run] print_dry_run @setup_interface.dry.init(payload) return end json_response = @setup_interface.init(payload) render_result = render_with_format(json_response, ) return 0 if render_result if [:json] print JSON.pretty_generate(json_response) print "\n" return end print "\n" print green,"Setup complete for remote #{@appliance_name} - #{@appliance_url}",reset,"\n" #print cyan, "You may now login with the command `login`.\n" # uh, just use Credentials.login(username, password, {save: true}) cmd_res = Morpheus::Cli::Login.new.login(['--username', payload['username'], '--password', payload['password'], '-q'] + ([:remote] ? ["-r",[:remote]] : [])) # print "\n" print cyan, "You are now logged in as the System Admin #{payload['username']}.\n" print reset #print "\n" if hubmode == 'skip' if ::Morpheus::Cli::OptionTypes::confirm("Would you like to apply your License Key now?", .merge({:default => true})) cmd_res = Morpheus::Cli::License.new.apply([] + ([:remote] ? ["-r",[:remote]] : [])) # license_is_valid = cmd_res != false end end if ::Morpheus::Cli::OptionTypes::confirm("Do you want to create the first group now?", .merge({:default => true})) cmd_res = Morpheus::Cli::Groups.new.add(['--use'] + ([:remote] ? ["-r",[:remote]] : [])) #print "\n" # if cmd_res != if ::Morpheus::Cli::OptionTypes::confirm("Do you want to create the first cloud now?", .merge({:default => true})) cmd_res = Morpheus::Cli::Clouds.new.add([] + ([:remote] ? ["-r",[:remote]] : [])) #print "\n" end # end end print "\n",reset end |
#teardown(args) ⇒ Object
this is just for testing new appliances really it can be used
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 |
# File 'lib/morpheus/cli/remote.rb', line 1214 def teardown(args) = {} optparse = Morpheus::Cli::OptionParser.new do|opts| opts. = subcommand_usage() (opts, , [:json, :dry_run, :quiet, :remote]) opts. = "Provides a way to uninitialize a fresh appliance. Useful for testing appliance setup." end optparse.parse!(args) # first arg as remote name otherwise the active appliance is connected to if args.count > 1 raise_command_error "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}" end if args[0] [:remote] = args[0] end connect() if !@appliance_name print yellow, "No active appliance, see `remote use`\n", reset return false end unless [:quiet] print yellow print "\n" puts "WARNING: You are about to reset your appliance installation." puts "It's only possible to perform teardown when the appliance has just been installed." puts "This provides a way to reset your appliance and run setup again." print reset print "\n" end unless [:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like teardown appliance '#{@appliance_name}'.", ) return 9, "aborted command" # new exit code for aborting confirmation end #@setup_interface = @api_client.setup # construct payload params = {} params.deep_merge!([:options].reject {|k,v| k.is_a?(Symbol) }) if [:options] # this works without any authentication! # it will allow anyone to use it, if there are no users/accounts in the system. #@api_client = establish_remote_appliance_connection(options) #@setup_interface = @api_client.setup @setup_interface = Morpheus::SetupInterface.new({url:@appliance_url,access_token:@access_token, very_ssl:false}) json_response = nil begin json_response = @setup_interface.teardown(params) if json_response['success'] != true print_error red, (json_response['msg'] || "Teardown failed").to_s, reset, "\n" return false end rescue RestClient::Exception => e print_rest_exception(e, ) return false end # ok, make the api request and render the response or print a message @setup_interface.setopts() if [:dry_run] print_dry_run @setup_interface.dry.teardown(params) return end json_response = @setup_interface.teardown(params) render_result = render_with_format(json_response, ) return 0 if render_result if [:quiet] return 0 end if json_response['msg'] print_green_success json_response['msg'] else print_green_success "Teardown complete for remote #{@appliance_name} - #{@appliance_url}. Now see `remote setup`" end return 0 end |
#unuse(args) ⇒ Object
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 |
# File 'lib/morpheus/cli/remote.rb', line 802 def unuse(args) = {} optparse = Morpheus::Cli::OptionParser.new do|opts| opts. = subcommand_usage() opts. = "" + "This clears the current remote appliance.\n" (opts, , []) end optparse.parse!(args) if args.count != 0 raise_command_error "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}" end #connect(options) @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance if !@appliance_name print yellow,"You are not using any appliance",reset,"\n" return 0 end Morpheus::Cli::Remote.clear_active_appliance() print cyan, "You are no longer using the appliance #{@appliance_name}", reset, "\n" # recalculate session variables ::Morpheus::Cli::Remote.recalculate_variable_map() return true end |
#update(args) ⇒ Object
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 |
# File 'lib/morpheus/cli/remote.rb', line 517 def update(args) = {} params = {} use_it = false is_insecure = nil new_name = nil optparse = Morpheus::Cli::OptionParser.new do|opts| opts. = subcommand_usage("[name]") opts.on(nil, "--name NAME", "Update the name of your remote appliance") do |val| new_name = val end opts.on("--url URL", String, "Update the url of your remote appliance") do |val| params[:host] = val end opts.on(nil, "--secure", "Prevent insecure HTTPS communication. This is enabled by default") do params[:secure] = true end opts.on(nil, "--insecure", "Allow insecure HTTPS communication. i.e. Ignore SSL errors.") do params[:insecure] = true end opts.on(nil, '--use', "Make this the current appliance" ) do use_it = true params[:active] = true end (opts, , [:quiet]) opts. = "This can be used to update remote appliance settings.\n" end optparse.parse!(args) if args.count != 1 print_error Morpheus::Terminal.angry_prompt puts_error "#{command_name} update expects argument [name]." puts_error optparse return 1 end appliance_name = args[0].to_sym appliance = ::Morpheus::Cli::Remote.load_remote(appliance_name) if !appliance raise_command_error "Remote appliance not found by the name '#{appliance_name}'" end # params[:url] = args[1] if args[1] if params.empty? print_error Morpheus::Terminal.angry_prompt puts_error "Specify at least one option to update" puts_error optparse return 1 end if params[:insecure] appliance[:insecure] = true elsif params[:secure] appliance.delete(:insecure) end if params[:url] || params[:host] appliance[:host] = params[:url] || params[:host] end ::Morpheus::Cli::Remote.save_remote(appliance_name, appliance) print_green_success "Updated remote #{appliance_name}" # todo: just go ahead and refresh it now... # _check(appliance_name, {:quiet => true}) appliance, check_json_response = ::Morpheus::Cli::Remote.refresh_remote(appliance_name) # print new appliance details _get(appliance[:name], {}) return 0, nil end |
#use(args) ⇒ Object
759 760 761 762 763 764 765 766 767 768 769 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 |
# File 'lib/morpheus/cli/remote.rb', line 759 def use(args) = {} optparse = Morpheus::Cli::OptionParser.new do|opts| opts. = subcommand_usage("[name]") (opts, , [:quiet]) opts. = "Make an appliance the current remote appliance.\n" + "This allows you to switch between your different appliances.\n" + "You may override this with the --remote option in your commands." end optparse.parse!(args) if args.count != 1 print_error Morpheus::Terminal.angry_prompt puts_error "#{command_name} use expects argument [name]." puts_error optparse return 1 end current_appliance_name, current_appliance_url = @appliance_name, @appliance_url appliance_name = args[0].to_sym appliance = ::Morpheus::Cli::Remote.load_remote(appliance_name) if !appliance raise_command_error "Remote appliance not found by the name '#{appliance_name}'" end # appliance = ::Morpheus::Cli::Remote.set_active_appliance(appliance_name) appliance[:active] = true appliance = ::Morpheus::Cli::Remote.save_remote(appliance_name, appliance) if [:quiet] return 0 end if current_appliance_name.to_s == appliance_name.to_s print green, "Using remote #{appliance_name} (still)", reset, "\n" else print green, "Using remote #{appliance_name}", reset, "\n" end # recalculate session variables ::Morpheus::Cli::Remote.recalculate_variable_map() return 0 end |