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

Inherits:
Object
  • Object
show all
Defined in:
lib/rbcli/state_storage/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



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rbcli/state_storage/remote_state_connectors/dynamodb.rb', line 42

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(:me, :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



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rbcli/state_storage/remote_state_connectors/dynamodb.rb', line 29

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



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

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



106
107
108
109
110
111
112
113
114
115
116
# File 'lib/rbcli/state_storage/remote_state_connectors/dynamodb.rb', line 106

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



129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/rbcli/state_storage/remote_state_connectors/dynamodb.rb', line 129

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



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

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



160
161
162
163
# File 'lib/rbcli/state_storage/remote_state_connectors/dynamodb.rb', line 160

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



92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/rbcli/state_storage/remote_state_connectors/dynamodb.rb', line 92

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



118
119
120
121
122
123
124
125
126
127
# File 'lib/rbcli/state_storage/remote_state_connectors/dynamodb.rb', line 118

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



88
89
90
# File 'lib/rbcli/state_storage/remote_state_connectors/dynamodb.rb', line 88

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

#unlockObject



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/rbcli/state_storage/remote_state_connectors/dynamodb.rb', line 143

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