Class: Rbcli::State::RemoteConnectors::DynamoDB

Inherits:
Object
  • Object
show all
Defined in:
lib/rbcli/stateful_systems/storagetypes/remote_state_connectors/dynamodb.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dynamodb_table, region, aws_access_key_id, aws_secret_access_key, locking: false, lock_timeout: 60) ⇒ DynamoDB

Returns a new instance of DynamoDB.



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rbcli/stateful_systems/storagetypes/remote_state_connectors/dynamodb.rb', line 22

def initialize dynamodb_table, region, aws_access_key_id, aws_secret_access_key, locking: false, lock_timeout: 60
	@region = region
	@dynamo_table_name = dynamodb_table
	@item_name = Rbcli::configuration[:scriptname]
	@locking = locking
	@scheduler = nil
	@lock_timeout = lock_timeout
	@exit_code_set = false
	@should_unlock_at_exit = false

	@dynamo_client = Aws::DynamoDB::Client.new(
			region: @region,
			access_key_id: aws_access_key_id,
			secret_access_key: aws_secret_access_key
	)
end

Class Method Details

.save_defaults(aws_access_key_id: nil, aws_secret_access_key: nil) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/rbcli/stateful_systems/storagetypes/remote_state_connectors/dynamodb.rb', line 9

def self.save_defaults aws_access_key_id: nil, aws_secret_access_key: nil
	Rbcli::Config::add_categorized_defaults :dynamodb_remote_state, 'Remote State Settings - requires DynamoDB', {
			access_key_id: {
					description: 'AWS Access Key ID -- leave as null to look for AWS credentials on system. See: https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/setup-config.html',
					value: aws_access_key_id
			},
			secret_access_key: {
					description: 'AWS Secret Access Key -- leave as null to look for AWS credentials on system.',
					value: aws_secret_access_key
			}
	}
end

Instance Method Details

#create_tableObject



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
# File 'lib/rbcli/stateful_systems/storagetypes/remote_state_connectors/dynamodb.rb', line 39

def create_table
	# We only need to create the table
	unless table_exists?
		print "Creating DynmoDB Table. Please wait..."
		@dynamo_client.create_table(
				{
						attribute_definitions: [
								{
										attribute_name: "Script Name",
										attribute_type: "S"
								}
						],
						key_schema: [
								{
										attribute_name: "Script Name",
										key_type: "HASH"
								}
						],
						provisioned_throughput: {
								read_capacity_units: 5,
								write_capacity_units: 5,
						},
						table_name: @dynamo_table_name,
				}
		)
		wait_for_table_creation
	end
end

#get_objectObject



86
87
88
89
90
91
92
93
94
95
96
# File 'lib/rbcli/stateful_systems/storagetypes/remote_state_connectors/dynamodb.rb', line 86

def get_object
	lock_or_wait
	item = @dynamo_client.get_item(
			{
					key: {'Script Name' => @item_name},
					table_name: @dynamo_table_name,
			}
	).item
	item.delete 'Script Name'
	item
end

#lockObject



109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/rbcli/stateful_systems/storagetypes/remote_state_connectors/dynamodb.rb', line 109

def lock
	@dynamo_client.put_item(
			{
					table_name: @dynamo_table_name,
					item: {
							'Script Name' => "#{@item_name}_lock",
							'locked' => true,
							'locked_until' => (Time.now + @lock_timeout).getutc.strftime('%s'),
							'locked_by' => Digest::SHA2.hexdigest(Mac.addr)
					}
			}
	)
end

#lock_or_wait(recursed = false) ⇒ Object



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
# File 'lib/rbcli/stateful_systems/storagetypes/remote_state_connectors/dynamodb.rb', line 145

def lock_or_wait recursed = false
	return true unless @locking
	delay_in_seconds = 2
	lockdata = get_lockdata

	should_claim = false

	# First, we identify if the lock is active
	if lockdata['locked']
		# If the lock is not ours, we have to check the expiration
		if lockdata['locked_by'] != Digest::SHA2.hexdigest(Mac.addr)
			# If the lock is not ours, and it has expired, we claim it
			if lockdata['locked_until'].to_i < Time.now.getutc.to_i
				should_claim = true
				# If the lock data is not ours and has not expired, we wait and try again
			else
				print 'Acquiring lock on DynamoDB. Please wait..' unless recursed
				print '.'
				sleep delay_in_seconds
				lock_or_wait true
			end

			# If the lock is ours, we check the expiry
		else
			# If the lock is ours and is close to expiry or has expired, we refresh it
			if lockdata['locked_until'].to_i < (Time.now - (@lock_timeout / 10)).getutc.to_i
				should_claim = true
				# If the lock is ours and is not near expiry, do nothing
			else
				# Do nothing! But do finish the string that's shown to the user
				puts 'done!' if recursed
			end
		end
	else # If clearly unlocked, we claim it
		should_claim = true
	end


	if should_claim
		# We attempt to get a lock then validate our success
		lock
		# If we succeeded then we set up a scheduler to ensure we keep it
		lockdata = get_lockdata
		if (lockdata['locked_by'] == Digest::SHA2.hexdigest(Mac.addr)) and (lockdata['locked_until'].to_i > Time.now.getutc.to_i)
			# Of course, if the scheduler already exists, we don't bother
			unless @scheduler
				@scheduler ||= Rufus::Scheduler.new
				@scheduler.every "#{@lock_timeout - 2}s" do
					lock
				end
				# We also make sure we release the lock at exit. In case this doesn't happen, the lock will expire on its own
				@should_unlock_at_exit = true
				unless @exit_code_set
					at_exit {unlock if @should_unlock_at_exit}
					@exit_code_set = true
				end
			end
			puts 'done!' if recursed
			# If we failed locking then we need to try the process all over again
		else
			print 'Error: Failed to lock DynamoDB. Retrying...'
			sleep delay_in_seconds
			lock_or_wait true
		end

	end

end

#locked?Boolean

Returns:

  • (Boolean)


140
141
142
143
# File 'lib/rbcli/stateful_systems/storagetypes/remote_state_connectors/dynamodb.rb', line 140

def locked?
	lockdata = get_lockdata
	(lockdata['locked']) and (lockdata['locked_until'].to_i > Time.now.getutc.to_i) and (lockdata['locked_by'] != Digest::SHA2.hexdigest(Mac.addr))
end

#object_exists?Boolean

Returns:

  • (Boolean)


72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/rbcli/stateful_systems/storagetypes/remote_state_connectors/dynamodb.rb', line 72

def object_exists?
	begin
		item = @dynamo_client.get_item(
				{
						key: {'Script Name' => @item_name},
						table_name: @dynamo_table_name,
				}
		)
		return (!item.item.nil?)
	rescue Aws::DynamoDB::Errors::ResourceNotFoundException
		return false
	end
end

#save_object(datahash) ⇒ Object



98
99
100
101
102
103
104
105
106
107
# File 'lib/rbcli/stateful_systems/storagetypes/remote_state_connectors/dynamodb.rb', line 98

def save_object datahash
	raise StandardError "DynamoDB has been locked by another user since the last change. Please try again later." if locked?
	lock_or_wait
	@dynamo_client.put_item(
			{
					table_name: @dynamo_table_name,
					item: datahash.merge({'Script Name' => @item_name})
			}
	)
end

#table_exists?Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/rbcli/stateful_systems/storagetypes/remote_state_connectors/dynamodb.rb', line 68

def table_exists?
	@dynamo_client.list_tables.table_names.to_a.include? @dynamo_table_name
end

#unlockObject



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/rbcli/stateful_systems/storagetypes/remote_state_connectors/dynamodb.rb', line 123

def unlock
	@dynamo_client.put_item(
			{
					table_name: @dynamo_table_name,
					item: {
							'Script Name' => "#{@item_name}_lock",
							'locked' => false,
							'locked_until' => Time.now.getutc.strftime('%s'),
							'locked_by' => false
					}
			}
	)
	@scheduler.shutdown :kill if @scheduler
	@should_unlock_at_exit = false
	@scheduler = nil
end