Skip to content

Commit b9491d2

Browse files
authored
Merge pull request #703 from stevenpost/mongosh
Use the mongosh command instead of the old mongo command
2 parents b6d3f5f + 263fc4f commit b9491d2

File tree

27 files changed

+167
-140
lines changed

27 files changed

+167
-140
lines changed

REFERENCE.md

+13-3
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ Data type: `String[1]`
6464

6565
Used to ensure that the package is installed, or that the package is absent/purged
6666

67-
Default value: `pick($mongodb::globals::version, 'present')`
67+
Default value: `pick($mongodb::globals::client_version, 'present')`
6868

6969
##### <a name="-mongodb--client--package_name"></a>`package_name`
7070

@@ -73,7 +73,7 @@ Data type: `String[1]`
7373
This setting can be used to specify the name of the package that should be installed.
7474
If not specified, the module will use whatever service name is the default for your OS distro.
7575

76-
Default value: `"mongodb-${mongodb::globals::edition}-shell"`
76+
Default value: `'mongodb-mongosh'`
7777

7878
### <a name="mongodb--globals"></a>`mongodb::globals`
7979

@@ -135,6 +135,7 @@ class {'mongodb::globals':
135135
The following parameters are available in the `mongodb::globals` class:
136136

137137
* [`version`](#-mongodb--globals--version)
138+
* [`client_version`](#-mongodb--globals--client_version)
138139
* [`manage_package_repo`](#-mongodb--globals--manage_package_repo)
139140
* [`repo_version`](#-mongodb--globals--repo_version)
140141
* [`use_enterprise_repo`](#-mongodb--globals--use_enterprise_repo)
@@ -153,6 +154,15 @@ If not specified, the module will ensure packages with `present`.
153154

154155
Default value: `undef`
155156

157+
##### <a name="-mongodb--globals--client_version"></a>`client_version`
158+
159+
Data type: `Optional[String[1]]`
160+
161+
The version of MongoDB Shell to install/manage.
162+
If not specified, the module will ensure packages with `present`.
163+
164+
Default value: `undef`
165+
156166
##### <a name="-mongodb--globals--manage_package_repo"></a>`manage_package_repo`
157167

158168
Data type: `Boolean`
@@ -967,7 +977,7 @@ Data type: `String`
967977

968978
The path to the custom mongosh rc file.
969979

970-
Default value: `"${facts['root_home']}/.mongorc.js"`
980+
Default value: `"${facts['root_home']}/.mongoshrc.js"`
971981

972982
##### <a name="-mongodb--server--service_manage"></a>`service_manage`
973983

lib/facter/is_master.rb

+3-4
Original file line numberDiff line numberDiff line change
@@ -39,17 +39,16 @@ def get_options_from_config(file)
3939

4040
Facter.add('mongodb_is_master') do
4141
setcode do
42-
if %w[mongo mongod].all? { |m| Facter::Util::Resolution.which m }
42+
if %w[mongosh mongod].all? { |m| Facter::Util::Resolution.which m }
4343
file = mongod_conf_file
4444
if file
4545
options = get_options_from_config(file)
46-
e = File.exist?('/root/.mongorc.js') ? 'load(\'/root/.mongorc.js\'); ' : ''
4746

4847
# Check if the mongodb server is responding:
49-
Facter::Core::Execution.exec("mongo --quiet #{options} --eval \"#{e}printjson(db.adminCommand({ ping: 1 }))\"")
48+
Facter::Core::Execution.exec("mongosh --quiet #{options} --eval \"EJSON.stringify(db.adminCommand({ ping: 1 }))\"")
5049

5150
if $CHILD_STATUS.success?
52-
Facter::Core::Execution.exec("mongo --quiet #{options} --eval \"#{e}db.isMaster().ismaster\"")
51+
Facter::Core::Execution.exec("mongosh --quiet #{options} --eval \"db.isMaster().ismaster\"")
5352
else
5453
'not_responding'
5554
end

lib/facter/mongodb_version.rb

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
Facter.add(:mongodb_version) do
44
setcode do
5-
if Facter::Core::Execution.which('mongo')
6-
mongodb_version = Facter::Core::Execution.execute('mongo --version 2>&1')
7-
%r{MongoDB shell version:?\s+v?([\w.]+)}.match(mongodb_version)[1]
5+
if Facter::Core::Execution.which('mongod')
6+
mongodb_version = Facter::Core::Execution.execute('mongod --version 2>&1')
7+
%r{^db version:?\s+v?([\w.]+)}.match(mongodb_version)[1]
88
end
99
end
1010
end

lib/puppet/provider/mongodb.rb

+18-15
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,15 @@
88
class Puppet::Provider::Mongodb < Puppet::Provider
99
# Without initvars commands won't work.
1010
initvars
11-
commands mongo: 'mongo'
11+
commands mongosh: 'mongosh'
1212

1313
# Optional defaults file
14-
def self.mongorc_file
15-
"load('#{Facter.value(:root_home)}/.mongorc.js'); " if File.file?("#{Facter.value(:root_home)}/.mongorc.js")
14+
def self.mongoshrc_file
15+
"load('#{Facter.value(:root_home)}/.mongoshrc.js'); " if File.file?("#{Facter.value(:root_home)}/.mongoshrc.js")
1616
end
1717

18-
def mongorc_file
19-
self.class.mongorc_file
18+
def mongoshrc_file
19+
self.class.mongoshrc_file
2020
end
2121

2222
def self.mongod_conf_file
@@ -74,7 +74,7 @@ def self.tls_invalid_hostnames(config = nil)
7474
config['tlsallowInvalidHostnames']
7575
end
7676

77-
def self.mongo_cmd(db, host, cmd)
77+
def self.mongosh_cmd(db, host, cmd)
7878
config = mongo_conf
7979

8080
args = [db, '--quiet', '--host', host]
@@ -101,7 +101,7 @@ def self.mongo_cmd(db, host, cmd)
101101
end
102102

103103
args += ['--eval', cmd]
104-
mongo(args)
104+
mongosh(args)
105105
end
106106

107107
def self.conn_string
@@ -111,9 +111,9 @@ def self.conn_string
111111
first_ip_in_list = bindip.split(',').first
112112
ip_real = case first_ip_in_list
113113
when '0.0.0.0'
114-
Facter.value(:fqdn)
114+
'127.0.0.1'
115115
when %r{\[?::0\]?}
116-
Facter.value(:fqdn)
116+
'::1'
117117
else
118118
first_ip_in_list
119119
end
@@ -135,11 +135,14 @@ def self.conn_string
135135
"#{ip_real}:#{port_real}"
136136
end
137137

138+
def conn_string
139+
self.class.conn_string
140+
end
141+
138142
def self.db_ismaster
139143
cmd_ismaster = 'db.isMaster().ismaster'
140-
cmd_ismaster = mongorc_file + cmd_ismaster if mongorc_file
141144
db = 'admin'
142-
res = mongo_cmd(db, conn_string, cmd_ismaster).to_s.split(%r{\n}).last.chomp
145+
res = mongosh_cmd(db, conn_string, cmd_ismaster).to_s.split(%r{\n}).last.chomp
143146
res.eql?('true')
144147
end
145148

@@ -156,14 +159,14 @@ def self.auth_enabled(config = nil)
156159
def self.mongo_eval(cmd, db = 'admin', retries = 10, host = nil)
157160
retry_count = retries
158161
retry_sleep = 3
159-
cmd = mongorc_file + cmd if mongorc_file
162+
cmd = mongoshrc_file + cmd if mongoshrc_file
160163

161164
out = nil
162165
begin
163166
out = if host
164-
mongo_cmd(db, host, cmd)
167+
mongosh_cmd(db, host, cmd)
165168
else
166-
mongo_cmd(db, conn_string, cmd)
169+
mongosh_cmd(db, conn_string, cmd)
167170
end
168171
rescue StandardError => e
169172
retry_count -= 1
@@ -174,7 +177,7 @@ def self.mongo_eval(cmd, db = 'admin', retries = 10, host = nil)
174177
end
175178
end
176179

177-
raise Puppet::ExecutionFailure, "Could not evaluate MongoDB shell command: #{cmd}" unless out
180+
raise Puppet::ExecutionFailure, "Could not evaluate MongoDB shell command: #{cmd}, with: #{e.message}" unless out
178181

179182
Puppet::Util::MongodbOutput.sanitize(out)
180183
end

lib/puppet/provider/mongodb_database/mongodb.rb

+3-3
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@
99
def self.instances
1010
require 'json'
1111

12-
pre_cmd = 'try { rs.secondaryOk() } catch (err) { rs.slaveOk() }'
13-
dbs = JSON.parse mongo_eval("#{pre_cmd};printjson(db.getMongo().getDBs())")
12+
pre_cmd = 'db.getMongo().setReadPref("primaryPreferred")'
13+
dbs = JSON.parse mongo_eval("#{pre_cmd};EJSON.stringify(db.getMongo().getDBs())")
1414

1515
dbs['databases'].map do |db|
1616
new(name: db['name'],
@@ -29,7 +29,7 @@ def self.prefetch(resources)
2929

3030
def create
3131
if db_ismaster
32-
out = mongo_eval('db.dummyData.insert({"created_by_puppet": 1})', @resource[:name])
32+
out = mongo_eval('db.dummyData.insertOne({"created_by_puppet": 1})', @resource[:name])
3333
raise "Failed to create DB '#{@resource[:name]}'\n#{out}" if %r{writeError} =~ out
3434
else
3535
Puppet.warning 'Database creation is available only from master host'

lib/puppet/provider/mongodb_replset/mongo.rb

+30-25
Original file line numberDiff line numberDiff line change
@@ -153,31 +153,36 @@ def get_hosts_status(members)
153153
members.select do |member|
154154
host = member['host']
155155
Puppet.debug "Checking replicaset member #{host} ..."
156-
status = rs_status(host)
157-
raise Puppet::Error, "Can't configure replicaset #{name}, host #{host} is not supposed to be part of a replicaset." if status.key?('errmsg') && status['errmsg'] == 'not running with --replSet'
158-
159-
if auth_enabled && status.key?('errmsg') && (status['errmsg'].include?('unauthorized') || status['errmsg'].include?('not authorized') || status['errmsg'].include?('requires authentication'))
160-
Puppet.warning "Host #{host} is available, but you are unauthorized because of authentication is enabled: #{auth_enabled}"
161-
alive.push(member)
162-
end
163-
164-
if status.key?('errmsg') && status['errmsg'].include?('no replset config has been received')
165-
Puppet.debug 'Mongo v4 rs.status() RS not initialized output'
166-
alive.push(member)
167-
end
168-
169-
if status.key?('set')
170-
raise Puppet::Error, "Can't configure replicaset #{name}, host #{host} is already part of another replicaset." if status['set'] != name
171-
172-
# This node is alive and supposed to be a member of our set
173-
Puppet.debug "Host #{host} is available for replset #{status['set']}"
174-
alive.push(member)
175-
elsif status.key?('info')
176-
Puppet.debug "Host #{host} is alive but unconfigured: #{status['info']}"
177-
alive.push(member)
156+
begin
157+
status = if host.split(':').first == Facter.value(:fqdn)
158+
rs_status(conn_string)
159+
else
160+
rs_status(host)
161+
end
162+
163+
if status.key?('set')
164+
raise Puppet::Error, "Can't configure replicaset #{name}, host #{host} is already part of another replicaset." if status['set'] != name
165+
166+
# This node is alive and supposed to be a member of our set
167+
Puppet.debug "Host #{host} is available for replset #{status['set']}"
168+
alive.push(member)
169+
elsif status.key?('info')
170+
Puppet.debug "Host #{host} is alive but unconfigured: #{status['info']}"
171+
alive.push(member)
172+
end
173+
rescue Puppet::ExecutionFailure => e
174+
raise Puppet::Error, "Can't configure replicaset #{name}, host #{host} is not supposed to be part of a replicaset." if e.message =~ %r{not running with --replSet}
175+
176+
if auth_enabled && (e.message.include?('unauthorized') || e.message.include?('not authorized') || e.message.include?('requires authentication'))
177+
Puppet.warning "Host #{host} is available, but you are unauthorized because of authentication is enabled: #{auth_enabled}"
178+
alive.push(member)
179+
elsif e.message.include?('no replset config has been received')
180+
Puppet.debug 'Mongo v4 rs.status() RS not initialized output'
181+
alive.push(member)
182+
else
183+
Puppet.warning "Can't connect to replicaset member #{host}."
184+
end
178185
end
179-
rescue Puppet::ExecutionFailure
180-
Puppet.warning "Can't connect to replicaset member #{host}."
181186
end
182187
alive.uniq!
183188
dead = members - alive
@@ -383,7 +388,7 @@ def mongo_command(command, host, retries = 4)
383388

384389
def self.mongo_command(command, host = nil, retries = 4)
385390
begin
386-
output = mongo_eval("printjson(#{command})", 'admin', retries, host)
391+
output = mongo_eval("EJSON.stringify(#{command})", 'admin', retries, host)
387392
rescue Puppet::ExecutionFailure => e
388393
Puppet.debug "Got an exception: #{e}"
389394
raise

lib/puppet/provider/mongodb_shard/mongo.rb

+3-3
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
mk_resource_methods
1515

16-
commands mongo: 'mongo'
16+
commands mongosh: 'mongosh'
1717

1818
def initialize(value = {})
1919
super(value)
@@ -152,8 +152,8 @@ def self.mongo_command(command, host = nil, _retries = 4)
152152
args = []
153153
args << '--quiet'
154154
args << ['--host', host] if host
155-
args << ['--eval', "printjson(#{command})"]
156-
output = mongo(args.flatten)
155+
args << ['--eval', "EJSON.stringify(#{command})"]
156+
output = mongosh(args.flatten)
157157
rescue Puppet::ExecutionFailure => e
158158
raise unless e =~ %r{Error: couldn't connect to server} && wait <= (2**max_wait)
159159

lib/puppet/provider/mongodb_user/mongodb.rb

+3-4
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,12 @@ def self.instances
1010
require 'json'
1111

1212
if db_ismaster
13-
script = 'printjson(db.system.users.find().toArray())'
13+
script = 'EJSON.stringify(db.system.users.find().toArray())'
1414
# A hack to prevent prefetching failures until admin user is created
15-
script = "try {#{script}} catch (e) { if (e.message.match(/not authorized on admin/)) { 'not authorized on admin' } else {throw e}}" if auth_enabled
15+
script = "try {#{script}} catch (e) { if (e.message.match(/requires authentication/) || e.message.match(/not authorized on admin/)) { 'not authorized on admin' } else {throw e}}" if auth_enabled
1616

1717
out = mongo_eval(script)
18-
19-
return [] if auth_enabled && out.include?('not authorized on admin')
18+
return [] if auth_enabled && (out.include?('requires authentication') || out.include?('not authorized on admin'))
2019

2120
users = JSON.parse out
2221

lib/puppet/type/mongodb_user.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ def insync?(_is)
117117
%w[mongodb mongod]
118118
end
119119

120-
autorequire(:mongodb_database) do
120+
autobefore(:mongodb_database) do
121121
self[:database]
122122
end
123123

manifests/client.pp

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111
# If not specified, the module will use whatever service name is the default for your OS distro.
1212
#
1313
class mongodb::client (
14-
String[1] $ensure = pick($mongodb::globals::version, 'present'),
15-
String[1] $package_name = "mongodb-${mongodb::globals::edition}-shell",
14+
String[1] $ensure = pick($mongodb::globals::client_version, 'present'),
15+
String[1] $package_name = 'mongodb-mongosh',
1616
) inherits mongodb::globals {
1717
package { 'mongodb_client':
1818
ensure => $ensure,

manifests/globals.pp

+5
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,10 @@
4141
# The version of MonogDB to install/manage.
4242
# If not specified, the module will ensure packages with `present`.
4343
#
44+
# @param client_version
45+
# The version of MongoDB Shell to install/manage.
46+
# If not specified, the module will ensure packages with `present`.
47+
#
4448
# @param manage_package_repo
4549
# Whether to manage MongoDB software repository.
4650
#
@@ -71,6 +75,7 @@
7175
#
7276
class mongodb::globals (
7377
Optional[String[1]] $version = undef,
78+
Optional[String[1]] $client_version = undef,
7479
Boolean $manage_package_repo = true,
7580
String[1] $repo_version = '5.0',
7681
Boolean $use_enterprise_repo = false,

manifests/server.pp

+1-1
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,7 @@
328328
Optional[Stdlib::Absolutepath] $pidfilepath = undef,
329329
String[4,4] $pidfilemode = '0644',
330330
Boolean $manage_pidfile = false,
331-
String $rcfile = "${facts['root_home']}/.mongorc.js",
331+
String $rcfile = "${facts['root_home']}/.mongoshrc.js",
332332
Boolean $service_manage = true,
333333
Optional[String[1]] $service_provider = undef,
334334
String[1] $service_name = 'mongod',

manifests/server/config.pp

+1-1
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@
177177
if $handle_creds {
178178
file { $rcfile:
179179
ensure => file,
180-
content => template('mongodb/mongorc.js.erb'),
180+
content => template('mongodb/mongoshrc.js.erb'),
181181
owner => 'root',
182182
group => 'root',
183183
mode => '0600',

spec/acceptance/database_spec.rb

+4-4
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ class { 'mongodb::globals':
2929
end
3030

3131
it 'creates the databases' do
32-
shell("mongo testdb1 --eval 'printjson(db.getMongo().getDBs())'")
33-
shell("mongo testdb2 --eval 'printjson(db.getMongo().getDBs())'")
32+
shell("mongosh testdb1 --eval 'EJSON.stringify(db.getMongo().getDBs())'")
33+
shell("mongosh testdb2 --eval 'EJSON.stringify(db.getMongo().getDBs())'")
3434
end
3535
end
3636

@@ -59,8 +59,8 @@ class { 'mongodb::globals':
5959
end
6060

6161
it 'creates the database' do
62-
shell("mongo testdb1 --port 27018 --eval 'printjson(db.getMongo().getDBs())'")
63-
shell("mongo testdb2 --port 27018 --eval 'printjson(db.getMongo().getDBs())'")
62+
shell("mongosh testdb1 --port 27018 --eval 'EJSON.stringify(db.getMongo().getDBs())'")
63+
shell("mongosh testdb2 --port 27018 --eval 'EJSON.stringify(db.getMongo().getDBs())'")
6464
end
6565
end
6666
end

spec/acceptance/mongos_spec.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ class { 'mongodb::globals':
5252
it { is_expected.to be_listening }
5353
end
5454

55-
describe command('mongo --version') do
55+
describe command('mongod --version') do
5656
its(:exit_status) { is_expected.to eq 0 }
5757
end
5858
end

0 commit comments

Comments
 (0)