Source

sbbdep / src / sbbdep / cachedb.cpp

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 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
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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
213
214
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
/*
--------------Copyright (c) 2010-2013 H a r a l d  A c h i t z---------------
-----------< h a r a l d dot a c h i t z at g m a i l dot c o m >------------
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/


#include <sbbdep/cachedb.hpp>
#include <sbbdep/cachesql.hpp>
#include <sbbdep/path.hpp>
#include <sbbdep/log.hpp>
#include <sbbdep/pkg.hpp>
#include <sbbdep/pkgname.hpp>
#include <sbbdep/pkgadmdir.hpp>
#include <sbbdep/config.hpp> // generated
#include <sbbdep/lddirs.hpp>

#include <a4sqlt3/sqlcommand.hpp>
#include <a4sqlt3/dataset.hpp>

#include <a4sqlt3/error.hpp>

#include <a4z/err.hpp>

#include <cstdlib>
#include <algorithm>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <queue>

namespace sbbdep {


class DbAction
{

  a4sqlt3::SqlCommand* m_cmdpkg;
  a4sqlt3::SqlCommand* m_cmddynlinked;
  a4sqlt3::SqlCommand* m_cmdrequired;
  a4sqlt3::SqlCommand* m_cmdrrunpath;
  a4sqlt3::SqlCommand* m_cmddelpkg;
  CacheDB& m_dbref;


public:
  DbAction( CacheDB& dbref )
  : m_cmdpkg(nullptr)
  , m_cmddynlinked(nullptr), m_cmdrequired(nullptr)
  , m_cmdrrunpath(nullptr),  m_cmddelpkg(nullptr)
  , m_dbref(dbref)
  {
    using namespace a4sqlt3;

    if(!(m_cmdpkg=m_dbref.getCommand("InsertPkgSQL"))) {
      m_cmdpkg = m_dbref.createStoredCommand("InsertPkgSQL", CacheSQL::InsertPkgSQL(),
          { DbValueType::Text, DbValueType::Text, DbValueType::Text,
              DbValueType::Text, DbValueType::Int64,
              DbValueType::Text, DbValueType::Int64 } ) ;
    }

    if(!(m_cmddynlinked=m_dbref.getCommand("InsertDynLinkedSQL"))) {
        m_cmddynlinked = m_dbref.createStoredCommand("InsertDynLinkedSQL", CacheSQL::InsertDynLinkedSQL(),
            {DbValueType::Int64,DbValueType::Text,
                DbValueType::Text, DbValueType::Text
                ,DbValueType::Text, DbValueType::Int64 } );
    }

    if(!(m_cmdrequired=m_dbref.getCommand("InsertRequiredSQL"))) {
        m_cmdrequired = m_dbref.createStoredCommand("InsertRequiredSQL", CacheSQL::InsertRequiredSQL(),
            {DbValueType::Int64,DbValueType::Text});
    }

    if(!(m_cmdrrunpath=m_dbref.getCommand("InsertRRunPathSQL"))) {
        m_cmdrrunpath = m_dbref.createStoredCommand("InsertRRunPathSQL", CacheSQL::InsertRRunPathSQL(),
            {DbValueType::Int64,DbValueType::Text, DbValueType::Text});
    }

    if(!(m_cmddelpkg=m_dbref.getCommand("DeletePkgByFullnameSQL"))) {
        m_cmddelpkg = m_dbref.createStoredCommand("DeletePkgByFullnameSQL", CacheSQL::DeletePkgByFullnameSQL(),
            {DbValueType::Text});
    }


  }//-----------------------------------------------------------------------------------------------



  void
  Store( const PkgName& pkgname, const Pkg::DynLinkedFiles& dllist, const int64_t& timestamp)
  {
    using a4sqlt3::DbValue ;

    LogInfo()<< "store " << pkgname.FullName() << std::endl;

    // what's going on here:
    // store the pkg,
    // to the pkg store all dynlinked infos
    // to each dynlinked info store Needed list and RunRPaths info

    // instead of capture this and writing always this->bla , for now ....


    auto store_pkg = [this](const PkgName& pkgname, const int64_t& timestamp) -> int64_t {
        a4sqlt3::DbValueList param_vals = {
           DbValue( pkgname.FullName() ) ,
           DbValue( pkgname.Name() ) ,
           DbValue( pkgname.Version() ) ,
           DbValue( pkgname.Arch() ) ,
           DbValue( pkgname.Build().Num() ) ,
           DbValue( pkgname.Build().Tag() ) ,
           DbValue( timestamp )
        };
        this->m_cmdpkg->Parameters().setValues(std::move(param_vals)) ;
        this->m_dbref.Execute(this->m_cmdpkg);
        return this->m_dbref.getLastInsertRowid() ;
      };


    auto store_dynlinked = [this](int64_t pkgid, const ElfFile& elf) -> int64_t {
      a4sqlt3::DbValueList param_vals = {
         DbValue( pkgid ) ,
         DbValue( elf.getName().Str() ) ,
         DbValue( elf.getName().getDir() ) ,
         DbValue( elf.getName().getBase() ) ,
          (elf.soName().size()> 0 ? DbValue(elf.soName()) : DbValue(a4sqlt3::DbValueType::Null) ) ,
         DbValue( elf.getArch() )
      };
      this->m_cmddynlinked->Parameters().setValues(std::move(param_vals)) ;;
      this->m_dbref.Execute(this->m_cmddynlinked);
      return this->m_dbref.getLastInsertRowid() ;

    };

    auto store_needed = [this](int64_t dynlinked_id, const std::string& needed) -> void {
      this->m_cmdrequired->Parameters().setValues({DbValue(dynlinked_id), DbValue(needed)}) ;
      this->m_dbref.Execute(this->m_cmdrequired);
    };

    auto store_rrunpath = [this](int64_t dynlinked_id,
        const std::string& rrunpath, const std::string& dynlinked_homedir ) -> void {
      this->m_cmdrrunpath->Parameters().setValues(
          {DbValue(dynlinked_id), DbValue(rrunpath), DbValue(dynlinked_homedir)}) ;
      this->m_dbref.Execute(this->m_cmdrrunpath);
    };


    int64_t pkgid = store_pkg(pkgname, timestamp) ;
    for(const ElfFile& elf : dllist)
      {
        int64_t dynlinked_id = store_dynlinked(pkgid, elf) ;

        for( const std::string& needed : elf.getNeeded() )
          {
            store_needed(dynlinked_id, needed);
          }

        for( const std::string& rrunpaht : elf.getRRunPaths() )
          {
            store_rrunpath(dynlinked_id, rrunpaht, elf.getName().getDir());
          }
      }


  }//-----------------------------------------------------------------------------------------------

  void Remove(const std::string& fullname)
  {
    LogInfo()<< "clear " << fullname << std::endl;
    m_cmddelpkg->Parameters().Nr(1).set(fullname) ;
    m_cmddelpkg->Run();
  }

};







CacheDB::CacheDB()
: a4sqlt3::Database(std::string(std::getenv("HOME")) + std::string("/sbbdep.cache")) //TODO wenn test vorbei nach .config/.. oder sonst wo
{
 
  Path p( _name );
  m_isNew = !p.isValid();

}
//--------------------------------------------------------------------------------------------------

CacheDB::CacheDB( const std::string& name )
: a4sqlt3::Database( name )
// , m_isNew( !Path(name).isValid() ) better readable in body
{

  Path p( _name );
  m_isNew = !p.isValid();

}
//--------------------------------------------------------------------------------------------------


bool
CacheDB::Open()
{
  
  if(  a4sqlt3::Database::Open() )
    {
      CacheSQL::register_own_sql_functions(_sql3db);

      checkVersion(
                sbbdep::MAJOR_VERSION,
                sbbdep::MINOR_VERSION ,
                sbbdep::PATCH_VERSION );

    }
  else
    return false;
  
  return true;
}
//--------------------------------------------------------------------------------------------------

bool
CacheDB::Create()
{

  LogInfo()<< "create cache " << _name << std::endl;

  if (a4sqlt3::Database::Create() )
    {
      try
        {
          Transaction transact(*this);
          Execute(CacheSQL::CreateSchemaSQL());

          transact.commit();
        }
      catch ( const a4z::Err& e )
        {
          LogError() << e << "\n ^ at creating db schema\n";
          A4Z_THROW_NESTED("");
        }

      CacheSQL::register_own_sql_functions(_sql3db);

      // possible call first sync/creation here and create indexes later..

      try
        {
          Transaction transact(*this);
          Execute(CacheSQL::CreateIndexes());
          Execute(CacheSQL::CreateViews());
          transact.commit();
        }
      catch ( const a4z::Err& e )
        {
          LogError() << e << "\n ^ at creating db indexes\n";
          A4Z_THROW_NESTED("");
        }


    }
  else
    return false;

  return true;
}
//--------------------------------------------------------------------------------------------------



void
CacheDB::checkVersion( int major, int minor, int patchlevel )
{
    {
      std::string sql = "select count(*) from sqlite_master where name='version';";

      a4sqlt3::DbValue rc = this->selectSingleValue(sql);

      if(rc.isNull())
        throw a4z::ErrorTodo();

      if( rc.getInt64() != 1 )
        {
          if( rc.getInt64() > 1 )
            {
              LogError() << "more than one entry in version table, confused and can not continue\n";
              throw a4z::ErrorTodo();
            }
          Execute(CacheSQL::CreateVersion(0, 1, 0)); // set default to 1, so update steps gi from one.
        }
    }

  // get db schema version from v
  auto calcMajorMinorVersion = [](int ma, int mi ) noexcept -> int
    {
      return (100000 + ma * 10000) + (1000 + mi * 100);
    };
  auto calcVersion = [](int ma, int mi, int pl ) noexcept -> int
    {
      return (100000 + ma * 10000) + (1000 + mi * 100) + pl;
    };
  using namespace a4sqlt3;
  auto getDbMajorMinorVersion = [calcMajorMinorVersion, this]() -> int
    {
      Dataset ds( {DbValueType::Int64, DbValueType::Int64} );
      this->Execute("SELECT major, minor FROM version", ds);
      return calcMajorMinorVersion(ds.getField(0).getInt64(), ds.getField(1).getInt64());
    };
  auto getDbVersion = [calcVersion, this]() -> int
    {
      Dataset ds({DbValueType::Int64, DbValueType::Int64, DbValueType::Int64});
      this->Execute("SELECT major, minor , patchlevel FROM version", ds);
      return calcVersion(ds.getField(0).getInt64(),
          ds.getField(1).getInt64(),ds.getField(2).getInt64());
    };

  if( calcVersion(major, minor, patchlevel) == getDbVersion() )
    return ;



  int app_version = calcVersion(major, minor, patchlevel);
  int db_version = getDbVersion();

  if( db_version < app_version )
    {
      if( getDbMajorMinorVersion() ==  calcMajorMinorVersion(0, 1) )
        {
          LogError() << "existing cache db was build with an old version of sbbdep.\n";
          LogError() << "please create a new cache by using the -c option or removing " <<
              _name << ".\n";
          LogError() << "Sorry for the inconvenience caused.\n\n" ;
          throw a4z::ErrorMessage("old db version in use");
        }

      Transaction trans(*this);
      if(db_version < calcVersion(0, 2, 1))
        {
          Execute("CREATE TABLE keyvalstore (key  NOT NULL,  value  NOT NULL);");
          Execute("create unique index  idx_keyvalstore_key on keyvalstore (key);");
          Execute("insert into keyvalstore (key, value ) values ('ldsoconf', 0);");
        }


      std::string sqcmd = "UPDATE version set major = " + std::to_string(major) +
          ", minor = " + std::to_string(minor) +
          ", patchlevel = " + std::to_string(patchlevel) + ";" ;
      Execute(sqcmd);
      trans.commit();
   }


#ifdef DEBUG
  if( calcVersion(major, minor, patchlevel) != getDbVersion() )
    throw a4z::ErrorNeverReach("version update incorrect");
#endif

}
//--------------------------------------------------------------------------------------------------

void
CacheDB::updateData(const StringVec& toremove, const StringVec& toinsert)
{

  LDDirs lddirs;

  a4sqlt3::Dataset dsldtime ;
  Execute("SELECT value FROM keyvalstore WHERE key='ldsoconf';", dsldtime);

  if(dsldtime.getRowCount()!= 1)
    throw a4z::ErrorMessage("keyval ldsoconf coutn != 1");

  if(lddirs.getLdSoConfTime() > dsldtime.getField(0).asInt64())
      {
        Transaction trans(*this);
        updateLdDirOnly(  StringVec(lddirs.getLdDirs().begin(), lddirs.getLdDirs().end()) ) ;
        trans.commit();
      }

  if(toremove.size()== 0 && toinsert.size()==0)
    {
      LogInfo() << "cache is up to date "<< std::endl;
      return ;
    }


  LogInfo() << "apply changes "<< std::endl;

// todo this needs only to be done if toinsert has data, if we just remove, this could be ignored

  std::thread loadlddirs( [&lddirs] (){
    lddirs.getLdDirs();
    lddirs.getLdLnkDirs();
  });




  struct ToStoreData
  {
    std::mutex mtx;
    std::condition_variable condition;
    bool newdata{false} ;

    std::atomic_bool running{false};

    std::vector<Pkg> pkgs;


    void add(const Pkg pkg) {
      std::unique_lock<std::mutex> lock(mtx);
      pkgs.push_back(pkg);
      newdata = true;
      condition.notify_one();
    }

  };

  auto persiter =[this](ToStoreData& tostore, DbAction& dbaction){

    while ( tostore.running )
      {
        std::unique_lock<std::mutex> lock(tostore.mtx);
        while (not tostore.newdata)
          tostore.condition.wait( lock );

        std::vector<Pkg> pkgs;
        std::swap(pkgs, tostore.pkgs);
        tostore.newdata = false;
        lock.unlock();

        for(Pkg& pkg : pkgs)
          {
            dbaction.Store(
                PkgName(pkg.getPath().getBase()),
                pkg.getDynLinked(),
                pkg.getPath().getLastModificationTime()) ;
          }
      }

      // check if something left to do
      { // here no lock should be required anymor cause if monitor is not running, no producers..
        std::vector<Pkg> pkgs;
        std::swap(pkgs, tostore.pkgs);
        for(Pkg& pkg : pkgs)
          {
            dbaction.Store(
                PkgName(pkg.getPath().getBase()),
                pkg.getDynLinked(),
                pkg.getPath().getLastModificationTime()) ;
          }
      }
  };


  class ToIndexData{
    std::mutex mtx;
    StringVec::const_iterator current;
    StringVec::const_iterator endpos;

  public:
    ToIndexData(const StringVec& data): current(data.begin()), endpos(data.end()) {}

    // as long as string not empty we can do something
    std::string pop(){

      std::unique_lock<std::mutex> lock(mtx);

      if( current == endpos )
        return std::string();

      std::string retval(*current);
      ++current;
      return retval;
    }
  };

  auto indexer = [this](ToIndexData& toindex, ToStoreData& tostore){

    for(;;)
      {
        std::string pkgpath = toindex.pop();

        if(pkgpath.empty())
          break;

        Path path(pkgpath);
        Pkg pkg  = Pkg::create( path );
        LogInfo()<< "index " << path.getBase() << std::endl;

        if (pkg.getType() != PkgType::Installed || not pkg.Load() )
          continue;

        tostore.add(pkg);

      }

  };


  DbAction dbaction(*this);
  Transaction transaction(*this);

  std::thread delwork;
  if(toremove.size() > 0)
    delwork = std::thread([&dbaction, &toremove](){
      for(auto& val : toremove)
        dbaction.Remove(val);
      });


  ToStoreData tostore;
  tostore.running = true ;

  // for indexing I need full path, so do this
  StringVec fullnames = toinsert;
  PkgAdmDir pkg_adm_dir;
  auto makefullpathname = [&pkg_adm_dir](std::string& s) ->std::string
      { return pkg_adm_dir.getDirName() + "/" + s ; } ;

  std::transform(fullnames.begin(), fullnames.end(),
       std::begin(fullnames), makefullpathname );

  ToIndexData toindex(fullnames);

  auto waitfor = [](std::thread& th){ if(th.joinable()) th.join(); };

  std::thread indexer1(indexer , std::ref(toindex), std::ref(tostore) );
  std::thread indexer2(indexer,  std::ref(toindex), std::ref(tostore) );

  waitfor(delwork);
  // important to wait here, reinstalled could have same name so must be deleted first

  std::thread storework(persiter, std::ref(tostore), std::ref(dbaction));



  waitfor(indexer1);
  waitfor(indexer2);


  {
    std::unique_lock<std::mutex> monitorlock(tostore.mtx);
    tostore.newdata = true;
    tostore.condition.notify_one();
    tostore.running = false;
    tostore.condition.notify_one(); // just to be sure to not run into troubles
  }

  waitfor(storework);


  LogInfo() << "wait for resolving symbolic links"<< std::endl;
  waitfor(loadlddirs);


  updateLdDirs(StringVec(lddirs.getLdDirs().begin(), lddirs.getLdDirs().end()) ,
        StringVec(lddirs.getLdLnkDirs().begin(), lddirs.getLdLnkDirs().end())
  );



  LogInfo() << "persist new information to disk\n";

  transaction.commit();

  LogInfo() << "run db analyzer\n";
  Execute("ANALYZE ;");

  m_isNew = false ;

}
//--------------------------------------------------------------------------------------------------

void
CacheDB::updateLdDirOnly(const StringVec& lddirs)
{
  using namespace a4sqlt3;


  SqlCommand* cmdlddir = getCommand("cmdlddir");
  if(not cmdlddir){
      cmdlddir = createStoredCommand("cmdlddir",
          CacheSQL::InsertLdDirSQL(),{DbValueType::Text});
  }

  Execute("DELETE FROM lddirs;");

  for(const std::string val : lddirs)
    {
      cmdlddir->Parameters().Nr(1).set(val);
      Execute(cmdlddir);
    }

  persistLdSoTime();

}
//--------------------------------------------------------------------------------------------------

void
CacheDB::persistLdSoTime()
{
  LDDirs lddirs;
  Execute("update keyvalstore set value = " +  std::to_string(lddirs.getLdSoConfTime()) + " ;") ;
}
//--------------------------------------------------------------------------------------------------

void
CacheDB::updateLdDirs(const StringVec& lddirs, const StringVec& ldlinkdirs)
{
  using namespace a4sqlt3;


  SqlCommand* cmdlddir = getCommand("cmdlddir");
  if(not cmdlddir){
      cmdlddir = createStoredCommand("cmdlddir",
          CacheSQL::InsertLdDirSQL(),{DbValueType::Text});
  }

  SqlCommand* cmdldlnkdir = getCommand("cmdldlnkdir");
  if(not cmdldlnkdir){
      cmdldlnkdir = createStoredCommand("cmdldlnkdir",
          CacheSQL::InsertLdLnkDirSQL(), {DbValueType::Text});
  }


  Execute("DELETE FROM lddirs;");
  Execute("DELETE FROM ldlnkdirs;");


  for(const std::string val : lddirs)
    {
      cmdlddir->Parameters().Nr(1).set(val);
      Execute(cmdlddir);
    }

  for(const std::string val : ldlinkdirs)
    {
      cmdldlnkdir->Parameters().Nr(1).set(val);
      Execute(cmdldlnkdir);
    }

  persistLdSoTime();
}
//--------------------------------------------------------------------------------------------------

int64_t
CacheDB::getLatestPkgTimeStamp()
{

  a4sqlt3::DbValue val = selectSingleValue(CacheSQL::MaxPkgTimeStamp());

  return val.isNull() ? 0 : val.getInt64() ;

}

//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
} // ns
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.