After installing Lens manually (not using a package manager file such as .deb or .rpm) the following will need to be done to allow protocol handling. This assumes that your linux distribution uses xdg-open and the xdg-* suite of programs for determining which application can handle custom URIs.
Create a file called lens.desktop in either ~/.local/share/applications/ or /usr/share/applications (if you have permissions and are installing Lens for all users).
That file should have the following contents, with <path/to/executable> being the absolute path to where you have installed the unpacked Lens executable:
1 2 3 4 5 6 7 8 9 10
[Desktop Entry] Name=Lens Exec=<path/to/executable> %U Terminal=false Type=Application Icon=lens StartupWMClass=Lens Comment=Lens - The Kubernetes IDE MimeType=x-scheme-handler/lens; Categories=Network;
Then run the following command:
1
$ xdg-settings set default-url-scheme-handler lens lens.desktop
If that succeeds (exits with code 0) then your Lens install should be set up to handle lens:// URIs.
Posted onEdited onInDevOps
,
LoggingWord count in article: 4.1kReading time ≈4 mins.
logrotate
The logrotate utility is designed to simplify the administration of log files on a system which generates a lot of log files. Logrotate allows for the automatic rotation compression, removal and mailing of log files. Logrotate can be set to handle a log file hourly, daily, weekly, monthly or when the log file gets to a certain size.
Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of conflicts with the data. It does this by checking whether another process has made changes to a record since it was opened, an ActiveRecord::StaleObjectError exception is thrown if that has occurred and the update is ignored.
If your class produces objects that never change, you can make these objects compile-time constants. To do this, define a const constructor and make sure that all instance variables are final.
By default, Active Record uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class Book, you should have a database table called books. The Rails pluralization mechanisms are very powerful, being capable of pluralizing (and singularizing) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the CamelCase form, while the table name must contain the words separated by underscores. Examples:
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically you should use transaction blocks whenever you have a number of statements that must be executed together or not at all.
For example:
1 2 3 4
ActiveRecord::Base.transaction do david.withdrawal(100) mary.deposit(100) end
This example will only take money from David and give it to Mary if neither withdrawal nor deposit raise an exception. Exceptions will force a ROLLBACK that returns the database to the state before the transaction began. Be aware, though, that the objects will not have their instance data returned to their pre-transactional state.
Different Active Record classes in a single transaction
Though the transaction class method is called on some Active Record class, the objects within the transaction block need not all be instances of that class. This is because transactions are per-database connection, not per-model.
In this example a balance record is transactionally saved even though transaction is called on the Account class:
1 2 3 4
Account.transaction do balance.save! account.save! end
The transaction method is also available as a model instance method. For example, you can also do this:
1 2 3 4
balance.transaction do balance.save! account.save! end
Transactions are not distributed across database connections
A transaction acts on a single database connection. If you have multiple class-specific databases, the transaction will not protect interaction among them. One workaround is to begin a transaction on each class whose models you alter:
1 2 3 4 5 6
Student.transaction do Course.transaction do course.enroll(student) student.units += course.units end end
This is a poor solution, but fully distributed transactions are beyond the scope of Active Record.
save and destroy are automatically wrapped in a transaction
Both #save and #destroy come wrapped in a transaction that ensures that whatever you do in validations or callbacks will happen under its protected cover. So you can use validations to check for values that the transaction depends on or you can raise exceptions in the callbacks to rollback, including after_* callbacks.
As a consequence changes to the database are not seen outside your connection until the operation is complete. For example, if you try to update the index of a search engine in after_save the indexer won’t see the updated record. The after_commit callback is the only one that is triggered once the update is committed. See below.
Abort Transactions
Any unhandled exception that occurs during the transaction will also cause it to be aborted. There are two common ways to raise these exceptions:
Using ActiveRecord methods ending with an exclamation-mark: save!, update!, destroy! etc.
Manually raising an exception
Use bang(!) method
In ActiveRecord, when a method name ends with an exclamation-mark (also called a “bang”), it will raise an exception on failure.
Let’s say we have a transaction that involves creating a new user account, while also updating the record of another user (the referrer):
1 2 3 4
ActiveRecord::Base.transaction do @new_user = User.create!(user_params) @referrer.update!(params[:reference_record]) end
The create! and update! methods will raise an exception if something goes wrong.
If we were to use the create and update methods (without the exclamation mark), they would indicate a failure via their return value, and the transaction would keep running.
Of course, we could always check the return value ourselves and “manually” raise an exception if we wanted to:
1 2 3 4 5
ActiveRecord::Base.transaction do @new_user = User.create(user_params) raiseActiveRecord::RecordInvalidunless@new_user.persisted? ... end
It doesn’t matter what kind of exception you raise. Any exception class will abort the transaction.
Also have in mind that exceptions thrown within a transaction block will be propagated (after triggering the ROLLBACK), so you should be ready to catch those in your application code.
Don’t forget to rescue the exception if you need to.
1 2 3 4 5 6 7
defcreate_referrer_account ActiveRecord::Base.transaction do ... raiseActiveRecord::RecordInvalidif@referrer.nil? rescueActiveRecord::RecordInvalid => exception # handle error here... end end
ActiveRecord::Rollback exception
One exception is the ActiveRecord::Rollback exception, which will trigger a ROLLBACK when raised, but not be re-raised by the transaction block.
1 2 3 4 5 6
ActiveRecord::Base.transaction do @new_user = User.create!(user_params) @referrer = User.find(params[:referrer_id]) raiseActiveRecord::Rollbackif@referrer.nil? @referrer.update!(params[:reference_record]) end
Warning: one should not catch ActiveRecord::StatementInvalid exceptions inside a transaction block. ActiveRecord::StatementInvalid exceptions indicate that an error occurred at the database level, for example when a unique constraint is violated. On some database systems, such as PostgreSQL, database errors inside a transaction cause the entire transaction to become unusable until it’s restarted from the beginning. Here is an example which demonstrates the problem:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Suppose that we have a Number model with a unique column called 'i'. Number.transaction do Number.create(i:0) begin # This will raise a unique constraint error... Number.create(i:0) rescueActiveRecord::StatementInvalid # ...which we ignore. end
# On PostgreSQL, the transaction is now unusable. The following # statement will cause a PostgreSQL error, even though the unique # constraint is no longer violated: Number.create(i:1) # => "PG::Error: ERROR: current transaction is aborted, commands # ignored until end of transaction block" end
One should restart the entire transaction if an ActiveRecord::StatementInvalid occurred.
Nested transactions
transaction calls can be nested. By default, this makes all database statements in the nested transaction block become part of the parent transaction. For example, the following behavior may be surprising:
1 2 3 4 5 6 7
User.transaction do User.create(username:'Kotori') User.transaction do User.create(username:'Nemu') raiseActiveRecord::Rollback end end
creates both “Kotori” and “Nemu”. Reason is the ActiveRecord::Rollback exception in the nested block does not issue a ROLLBACK. Since these exceptions are captured in transaction blocks, the parent block does not see it and the real transaction is committed.
In order to get a ROLLBACK for the nested transaction you may ask for a real sub-transaction by passing requires_new: true. If anything goes wrong, the database rolls back to the beginning of the sub-transaction without rolling back the parent transaction. If we add it to the previous example:
1 2 3 4 5 6 7
User.transaction do User.create(username:'Kotori') User.transaction(requires_new:true) do User.create(username:'Nemu') raiseActiveRecord::Rollback end end
There are two types of callbacks associated with committing and rolling back transactions: after_commit and after_rollback.
after_commit callbacks are called on every record saved or destroyed within a transaction immediately after the transaction is committed.
after_rollback callbacks are called on every record saved or destroyed within a transaction immediately after the transaction or savepoint is rolled back.
These callbacks are useful for interacting with other systems since you will be guaranteed that the callback is only executed when the database is in a permanent state. For example, after_commit is a good spot to put in a hook to clearing a cache since clearing it from within a transaction could trigger the cache to be regenerated before the database is updated.
Transaction isolation
If your database supports setting the isolation level for a transaction, you can set it like so:
1 2 3
Post.transaction(isolation::serializable) do # ... end
Valid isolation levels are:
:read_uncommitted
:read_committed
:repeatable_read
:serializable
You should consult the documentation for your database to understand the semantics of these different levels:
An ActiveRecord::TransactionIsolationError will be raised if:
The adapter does not support setting the isolation level
You are joining an existing open transaction
You are creating a nested (savepoint) transaction
The mysql2 and postgresql adapters support setting the transaction isolation level.
Caveats
If you’re on MySQL, then do not use Data Definition Language (DDL) operations in nested transactions blocks that are emulated with savepoints. That is, do not execute statements like ‘CREATE TABLE’ inside such blocks. This is because MySQL automatically releases all savepoints upon executing a DDL operation. When transaction is finished and tries to release the savepoint it created earlier, a database error will occur because the savepoint has already been automatically released. The following example demonstrates the problem:
1 2 3 4 5 6
Model.connection.transaction do# BEGIN Model.connection.transaction(requires_new:true) do# CREATE SAVEPOINT active_record_1 Model.connection.create_table(...) # active_record_1 now automatically released end# RELEASE SAVEPOINT active_record_1 # ^^^^ BOOM! database error! end
Note that “TRUNCATE” is also a MySQL DDL statement!
Instance Public methods
after_commit(*args, &block)
This callback is called after a record has been created, updated, or destroyed.
You can specify that the callback should only be fired by a certain action with the :on option:
Using ActiveRecord::CounterCache::ClassMethods to Prevent Race Conditions
Race conditions are arguably the most insidious kind of bug; they’re intermittent, subtle, and most likely to occur in production. ActiveRecord’s update_counter and other methods provides us with a convenient way to avoid race conditions when incrementing or decrementing values in the database.