Class: Yast::SnapperClass

Inherits:
Module
  • Object
show all
Includes:
Logger
Defined in:
../../src/modules/Snapper.rb

Defined Under Namespace

Classes: Tree

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Instance Attribute Details

- (Object) current_config

Returns the value of attribute current_config



37
38
39
# File '../../src/modules/Snapper.rb', line 37

def current_config
  @current_config
end

- (Object) current_subvolume (readonly)

Returns the value of attribute current_subvolume



38
39
40
# File '../../src/modules/Snapper.rb', line 38

def current_subvolume
  @current_subvolume
end

Instance Method Details

- (Object) CreateSnapshot(args)

Create new snapshot Return true on success



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File '../../src/modules/Snapper.rb', line 259

def CreateSnapshot(args)

  case args["type"]
  when "single"
    SnapperDbus.create_single_snapshot(@current_config, args["description"], args["cleanup"],
                                       args["userdata"])
  when "pre"
    SnapperDbus.create_pre_snapshot(@current_config, args["description"], args["cleanup"],
                                    args["userdata"])
  when "post"
    SnapperDbus.create_post_snapshot(@current_config, args["pre"], args["description"],
                                     args["cleanup"], args["userdata"])
  end

  return true

rescue Exception => e
  Report.Error(_("Failed to create new snapshot:" + "\n" + e.message))
  return false
end

- (Object) DeleteSnapshot(nums)

Delete existing snapshot Return true on success



299
300
301
302
303
304
305
306
307
308
309
# File '../../src/modules/Snapper.rb', line 299

def DeleteSnapshot(nums)

  SnapperDbus.delete_snapshots(@current_config, nums)

  return true

rescue Exception => e
  Report.Error(_("Failed to delete snapshot:" + "\n" + e.message))
  return false

end

- (Object) get_config



103
104
105
106
107
108
109
110
111
# File '../../src/modules/Snapper.rb', line 103

def get_config()

  return SnapperDbus.get_config(@current_config)

rescue Exception => e
  Report.Error(_("Failed to get config:" + "\n" + e.message))
  return {}

end

- (Object) GetFileFullPath(file)

Return the full path to the given file from currently selected configuration (subvolume) GetFileFullPath (“/testfile.txt”) -> /abc/testfile.txt for /abc subvolume

Parameters:

  • file (String)

    path, relatively to current config



138
139
140
# File '../../src/modules/Snapper.rb', line 138

def GetFileFullPath(file)
  return prepend_subvolume(file)
end

- (Object) GetFileMode(file)

Return the given file mode as octal number



371
372
373
374
375
376
377
378
379
380
381
# File '../../src/modules/Snapper.rb', line 371

def GetFileMode(file)
  out = Convert.to_map(
    SCR.Execute(
      path(".target.bash_output"),
      Builtins.sformat("/bin/stat --printf=%%a '%1'", String.Quote(file))
    )
  )
  mode = Ops.get_string(out, "stdout", "")
  return 644 if mode == nil || mode == ""
  Builtins.tointeger(mode)
end

- (Object) GetFileModification(file, old, new)

Describe what was done with given file between given snapshots - when new is 0, meaning is 'current system'



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
# File '../../src/modules/Snapper.rb', line 145

def GetFileModification(file, old, new)
  ret = {}
  file1 = Builtins.sformat("%1%2", GetSnapshotPath(old), file)
  file2 = Builtins.sformat("%1%2", GetSnapshotPath(new), file)
  file2 = GetFileFullPath(file) if new == 0

  Builtins.y2milestone("comparing '%1' and '%2'", file1, file2)

  if FileUtils.Exists(file1) && FileUtils.Exists(file2)
    status = ["no_change"]
    out = Convert.to_map(
      SCR.Execute(
        path(".target.bash_output"),
        Builtins.sformat(
          "/usr/bin/diff -u '%1' '%2'",
          String.Quote(file1),
          String.Quote(file2)
        )
      )
    )
    if Ops.get_string(out, "stderr", "") != ""
      Builtins.y2warning("out: %1", out)
      Ops.set(ret, "diff", Ops.get_string(out, "stderr", ""))
    # the file diff
    elsif Ops.get(out, "stdout") != ""
      status = ["diff"]
      ret["diff"] = out["stdout"].encode(Encoding::UTF_8, { :invalid => :replace })
    end

    # check mode and ownerships
    out = Convert.to_map(
      SCR.Execute(
        path(".target.bash_output"),
        Builtins.sformat(
          "ls -ld -- '%1' '%2' | cut -f 1,3,4 -d ' '",
          String.Quote(file1),
          String.Quote(file2)
        )
      )
    )
    parts = Builtins.splitstring(Ops.get_string(out, "stdout", ""), " \n")

    if Ops.get(parts, 0, "") != Ops.get(parts, 3, "")
      status = Builtins.add(status, "mode")
      Ops.set(ret, "mode1", Ops.get(parts, 0, ""))
      Ops.set(ret, "mode2", Ops.get(parts, 3, ""))
    end
    if Ops.get(parts, 1, "") != Ops.get(parts, 4, "")
      status = Builtins.add(status, "user")
      Ops.set(ret, "user1", Ops.get(parts, 1, ""))
      Ops.set(ret, "user2", Ops.get(parts, 4, ""))
    end
    if Ops.get(parts, 2, "") != Ops.get(parts, 5, "")
      status = Builtins.add(status, "group")
      Ops.set(ret, "group1", Ops.get(parts, 2, ""))
      Ops.set(ret, "group2", Ops.get(parts, 5, ""))
    end
    Ops.set(ret, "status", status)
  elsif FileUtils.Exists(file1)
    Ops.set(ret, "status", ["removed"])
  elsif FileUtils.Exists(file2)
    Ops.set(ret, "status", ["created"])
  else
    Ops.set(ret, "status", ["none"])
  end
  deep_copy(ret)
end

- (Object) GetSnapshotPath(snapshot_num)

Return the path to given snapshot



124
125
126
127
128
129
130
131
132
# File '../../src/modules/Snapper.rb', line 124

def GetSnapshotPath(snapshot_num)

  return SnapperDbus.get_mount_point(@current_config, snapshot_num)

rescue Exception => e
  Report.Error(_("Failed to get snapshot mount point:" + "\n" + e.message))
  return ""

end

- (Object) Init

Init snapper (get configs and snapshots) Return true on success



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
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
364
365
366
367
# File '../../src/modules/Snapper.rb', line 314

def Init

  # We do not set help text here, because it was set outside
  Progress.New(
   # Snapper read dialog caption
    _("Initializing Snapper"),
    " ",
    2,
    [
      # Progress stage 1/2
      _("Read list of configurations"),
      # Progress stage 2/2
      _("Read list of snapshots"),
    ],
    [
      # Progress step 1/2
      _("Reading list of configurations"),
      # Progress step 2/2
      _("Reading list of snapshots"),
      # Progress finished
      _("Finished")
    ],
    ""
  )

  Progress.NextStage

  begin
    ReadConfigs()
  rescue Exception => e
    Report.Error(_("Querying snapper configurations failed:") + "\n" + e.message)
    return false
  end

  if @configs.empty?
    Report.Error(_("No snapper configurations exist. You have to create one or more
configurations to use yast2-snapper. The snapper command line
tool can be used to create configurations."))
  end

  Progress.NextStage

  begin
    ReadSnapshots()
  rescue Exception => e
    Report.Error(_("Querying snapper snapshots failed:") + "\n" + e.message)
    return false
  end

  Progress.NextStage

  return true

end

- (Object) main



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 '../../src/modules/Snapper.rb', line 41

def main
  Yast.import "UI"
  textdomain "snapper"

  Yast.import "FileUtils"
  Yast.import "Label"
  Yast.import "Progress"
  Yast.import "Report"
  Yast.import "String"
  Yast.import "SnapperDbus"

  # global list of all snapshot
  @snapshots = []

  @selected_snapshot = {}

  # mapping of snapshot number to index in snapshots list
  @id2index = {}

  # list of configurations
  @configs = []

  @current_config = ""
  @current_subvolume = ""

end

- (Object) ModifySnapshot(args)

Modify existing snapshot Return true on success



283
284
285
286
287
288
289
290
291
292
293
294
# File '../../src/modules/Snapper.rb', line 283

def ModifySnapshot(args)

  SnapperDbus.set_snapshot(@current_config, args["num"], args["description"], args["cleanup"],
                           args["userdata"])

  return true

rescue Exception => e
  Report.Error(_("Failed to modify snapshot:" + "\n" + e.message))
  return false

end

- (Object) prepend_subvolume(filename)



114
115
116
117
118
119
120
# File '../../src/modules/Snapper.rb', line 114

def prepend_subvolume(filename)
  if @current_subvolume == "/"
    return filename
  else
    return @current_subvolume + filename
  end
end

- (Object) ReadConfigs



242
243
244
245
246
247
248
249
250
251
252
253
254
# File '../../src/modules/Snapper.rb', line 242

def ReadConfigs

  @configs = SnapperDbus.list_configs()

  if @configs.include?("root")
    self.current_config = "root"
  elsif !@configs.empty?
    self.current_config = @configs[0]
  else
    self.current_config = ""
  end

end

- (Object) ReadModifiedFilesTree(from, to)

Return Tree of files modified between given snapshots Map is recursively describing the filesystem structure; helps to build Tree widget contents



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File '../../src/modules/Snapper.rb', line 86

def ReadModifiedFilesTree(from, to)

  SnapperDbus.create_comparison(@current_config, from, to)
  files = SnapperDbus.get_files(@current_config, from, to)
  SnapperDbus.delete_comparison(@current_config, from, to)

  root = Tree.new("", nil)

  files.each do |file|
    root.add(file["filename"], file["status"])
  end

  return root

end

- (Object) ReadSnapshots

Read the list of snapshots



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
# File '../../src/modules/Snapper.rb', line 215

def ReadSnapshots

  snapshot_maps = SnapperDbus.list_snapshots(@current_config)

  @snapshots = []
  i = 0
  Builtins.foreach(snapshot_maps) do |snapshot|
    id = Ops.get_integer(snapshot, "num", 0)
    next if id == 0 # ignore the 'current system'

    if snapshot["type"] == :PRE
      snapshot_maps.each do |x|
        if x["type"] == :POST && x["pre_num"] == snapshot["num"]
          snapshot["post_num"] = x["num"]
        end
      end
    end

    log.debug("snapshot:#{snapshot}")
    @snapshots = Builtins.add(@snapshots, snapshot)
    Ops.set(@id2index, id, i)
    i = Ops.add(i, 1)
  end
  true
end

- (Object) RestoreFiles(snapshot_num, files)

Copy given files from selected snapshot to current filesystem

Parameters:

  • snapshot_num (Fixnum)

    snapshot identifier

  • files (Array<String>)

    list of full paths to files (but excluding subvolume)

Returns:

  • success



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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
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
# File '../../src/modules/Snapper.rb', line 387

def RestoreFiles(snapshot_num, files)
  files = deep_copy(files)
  ret = true
  Builtins.y2milestone("going to restore files %1", files)

  UI.OpenDialog(
    Opt(:decorated),
    HBox(
      HSpacing(1.5),
      VBox(
        HSpacing(60),
        # label for log window
        LogView(Id(:log), _("Restoring Files..."), 8, 0),
        ProgressBar(Id(:progress), "", Builtins.size(files), 0),
        PushButton(Id(:ok), Label.OKButton)
      ),
      HSpacing(1.5)
    )
  )

  UI.ChangeWidget(Id(:ok), :Enabled, false)
  progress = 0
  Builtins.foreach(files) do |file|
    UI.ChangeWidget(Id(:progress), :Value, progress)
    orig = Ops.add(GetSnapshotPath(snapshot_num), file)
    full_path = GetFileFullPath(file)
    dir = Builtins.substring(
      full_path,
      0,
      Builtins.findlastof(full_path, "/")
    )
    if !FileUtils.Exists(orig)
      SCR.Execute(
        path(".target.bash"),
        Builtins.sformat("/bin/rm -rf -- '%1'", String.Quote(full_path))
      )
      Builtins.y2milestone("removing '%1' from system", full_path)
      # log entry (%1 is file name)
      UI.ChangeWidget(
        Id(:log),
        :LastLine,
        Builtins.sformat(_("Deleted %1\n"), full_path)
      )
    elsif FileUtils.CheckAndCreatePath(dir)
      Builtins.y2milestone(
        "copying '%1' to '%2' (dir: %3)",
        orig,
        file,
        dir
      )
      if FileUtils.IsDirectory(orig) == true
        stat = Convert.to_map(SCR.Read(path(".target.stat"), orig))
        if !FileUtils.Exists(full_path)
          SCR.Execute(path(".target.mkdir"), full_path)
        end
        SCR.Execute(
          path(".target.bash"),
          Builtins.sformat(
            "/bin/chown -- %1:%2 '%3'",
            Ops.get_integer(stat, "uid", 0),
            Ops.get_integer(stat, "gid", 0),
            String.Quote(full_path)
          )
        )
        SCR.Execute(
          path(".target.bash"),
          Builtins.sformat(
            "/bin/chmod -- %1 '%2'",
            GetFileMode(orig),
            String.Quote(full_path)
          )
        )
      else
        SCR.Execute(
          path(".target.bash"),
          Builtins.sformat(
            "/bin/cp -a -- '%1' '%2'",
            String.Quote(orig),
            String.Quote(full_path)
          )
        )
      end
      UI.ChangeWidget(Id(:log), :LastLine, Ops.add(full_path, "\n"))
    else
      Builtins.y2milestone(
        "failed to copy file '%1' to '%2' (dir: %3)",
        orig,
        full_path,
        dir
      )
      # log entry (%1 is file name)
      UI.ChangeWidget(
        Id(:log),
        :LastLine,
        Builtins.sformat(_("%1 skipped\n"), full_path)
      )
    end
    Builtins.sleep(100)
    progress = Ops.add(progress, 1)
  end

  UI.ChangeWidget(Id(:progress), :Value, progress)
  UI.ChangeWidget(Id(:ok), :Enabled, true)

  UI.UserInput
  UI.CloseDialog

  ret
end

- (Object) string_to_userdata(string)

convert string with userdata to a hash “a=1, b=2” -> { “a” => “1”, “b” => “2” }



507
508
509
510
511
512
513
514
515
# File '../../src/modules/Snapper.rb', line 507

def string_to_userdata(string)
  string.split(",").map do |s|
    if s.include?("=")
      s.split("=", 2).map { |t| t.strip }
    else
      [ s.strip, "" ]
    end
  end.to_h
end

- (Object) userdata_to_string(userdata)

convert hash with userdata to a string { “a” => “1”, “b” => “2” } -> “a=1, b=2”



500
501
502
# File '../../src/modules/Snapper.rb', line 500

def userdata_to_string(userdata)
  return userdata.map { |k, v| "#{k}=#{v}" }.join(", ")
end