Rozwiązanie problemów z zależnościami pakietu poprzez synonimy

Problem

Biorę udział w utrzymywaniu pewnego systemu typu ODS. Jednym z poważniejszych problemów podczas wgrywania poprawek jest sprawa zależności między pakietami. Przypuśćmy, że trzeba zmienić pakiet A, od którego zależą pakiety B1 i B2, które są wykorzystywane w ramach jakiejś sesji. Zmiana w A powoduje, że najbliższe uruchomienia pakietów B1 lub B2 bez tworzenia nowej sesji zakończą się błędem “ORA-04061: existing state of package has been invalidated”, jeśli tylko w A są jakiekolwiek zmienne globalne. To zachowanie Oracle’a wynika z faktu, że zmienne globalnych pakietów trwają przez cały czas życia sesji. Przy zmianie kodu pakietu mogły się one zmienić, dlatego muszą zostać zainicjowane na nowo. Ponieważ zresetowanie zmiennych w czasie trwania sesji mogłoby prowadzić do niespójności – Oracle rzuca opisany powyżej wyjątek. Ten mechanizm jest dokładniej opisany na stronie
http://oraclequirks.blogspot.com/2007/03/ora-04061-existing-state-of-package-has.html Zmiana pakietu – zarówno specyfikacji jak i ciała pakietu – nie jest możliwa jeśli coś z niego korzysta – w takim wypadku komenda zastąpienia pakietu przez nową wersję ( CREATE OR REPLACE PACKAGE [BODY]) czeka aż pakiet przestanie być używany. Ale wystarczy, aby jakiś nowy proces zaczynał korzystać z pakietu zanim stary przestanie to robić i następuje zagłodzenie. Nie można wgrać nowej wersji pakietu. Takie zjawiska bardzo utrudniają wdrażanie, trzeba zabijać procesy korzystające ze zmienianego pakietu. Wypracowałem nawet skrypt, który zabija wszystkie sesje blokujące jakąś sesję uruchomioną z mojego komputera i mojego użytkownika systemu operacyjnego:

DECLARE
  CURSOR c_sql_hist(pp_machine VARCHAR2, pp_osuser VARCHAR2) IS
    SELECT ash.blocking_session, ash.blocking_session_status, ash.blocking_session_serial#, s.program, s.module, s.action
      FROM v$active_session_history ash
      JOIN v$session s ON ash.blocking_session = s.sid
                      AND ash.blocking_session_serial# = s.serial#
     WHERE ash.session_id in ( select sid from v$session where machine = pp_machine
     and osuser = pp_osuser )
       AND ash.sample_time > SYSDATE - 2 / 24 / 3600
     ORDER BY sample_time DESC;
  v_r c_sql_hist%ROWTYPE;

  v_my_machine v$session.MACHINE%TYPE;
  v_my_osuser v$session.osuser%TYPE;
BEGIN
  select machine, osuser into v_my_machine, v_my_osuser from v$session
  where sid = ( Select Sid from v$mystat where rownum = 1);

  for i in 1..10000 loop  -- just to prevent infinite execution
    dbms_output.put_line('step: ' || i );
    OPEN c_sql_hist(v_my_machine, v_my_osuser);
    FETCH c_sql_hist
      INTO v_r;
    IF NOT c_sql_hist%NOTFOUND THEN
      dbms_output.put_line(v_r.blocking_session || ' ' || v_r.blocking_session_status || ' ' || v_r.blocking_session_serial# || ' ' || v_r.program || ' ' ||
                           v_r.module || ' ' || v_r.action);
      execute immediate ' ALTER SYSTEM KILL SESSION ''' || v_r.blocking_session || ',' || v_r.blocking_session_serial# || '''';
    else
      exit;
    END IF;
    CLOSE c_sql_hist;
    dbms_lock.sleep(0.5); -- sleep is used to get new blocking sessions
  end loop;
END;

Opisane powyżej problemy z zależnościami doprowadziły do sytuacji, w których różne pakiety narzędziowe, które powinny być zgromadzone w jednym centralnym schemacie zostały skopiowane do wszystkich schematów. Dzięki temu można je zmieniać bez konieczności zabijania wszystkich procesów działających na bazie, ale jest to rozwiązanie fatalne z punktu widzenia utrzymania kodu.

Rozwiązanie

Stosowanym przez nas rozwiązaniem tego problemu jest, aby odwołania do pakietów odbywały się poprzez synonimy. Jeśli jest potrzeba zmienić pakiet – tworzymy jego nową wersję a po przetestowaniu przepina się synonim, aby na nią wskazywał. Najbliższe uruchomienie tego synonimu w ramach sesji powoduje, że uruchamiany jest nowy pakiet. Jego zmienne są inicjalizowane na nowo, ale nie jest to problem, ponieważ pełnią funkcje cache’a a nie służą do przechowywania stanu. Występuje dodatkowe ograniczenie, że nie mogą chodzić równocześnie dwie wersje tej samej procedury lub pakietu, których synonimy wskazują na odmienne obiekty. Dlatego jeśli uruchomi się B1, przepnie synonim na A_v2, po czym ponownie uruchomi B1 (pośrednio lub bezpośrednio) to to drugie uruchomienie B1 nie rozpocznie się dopóki pierwsze – na starym synonimie – się nie skończy. Nie jest to jednak praktyczny problem. Opisane obejście pozwala na sprawniejszy rozwój i wdrażanie kodu bazodanowego. Konieczna jest tylko świadomość działania mechanizmu i powyższych ograniczeń. Należało również wypracować praktykę nazewnictwa (przykładowo dodawanie na końcu nazwy TO_CHAR(sysdate, ‘$MM_DD’) czyli znaku dolara oraz miesiącu i dnia wdrożenia wersji). Konieczne jest również nadanie innym schematom tych samych praw do nowej wersji pakietu, które mieli do starej wersji.

You May Also Like

Grails session timeout without XML

This article shows clean, non hacky way of configuring featureful event listeners for Grails application servlet context. Feat. HttpSessionListener as a Spring bean example with session timeout depending on whether user account is premium or not.

Common approaches

Speaking of session timeout config in Grails, a default approach is to install templates with a command. This way we got direct access to web.xml file. Also more unnecessary files are created. Despite that unnecessary files are unnecessary, we should also remember some other common knowledge: XML is not for humans.

Another, a bit more hacky, way is to create mysterious scripts/_Events.groovy file. Inside of which, by using not less enigmatic closure: eventWebXmlEnd = { filename -> ... }we can parse and hack into web.xml with a help of XmlSlurper.
Even though lot of Grails plugins do it similar way, still it’s not really straightforward, is it? Besides, where’s the IDE support? Hello!?

Examples of both above ways can be seen on StackOverflow.

Simpler and cleaner way

By adding just a single line to the already generated init closure we have it done:
class BootStrap {

def init = { servletContext ->
servletContext.addListener(OurListenerClass)
}
}

Allrighty, this is enough to avoid XML. Sweets are served after the main course though :)

Listener as a Spring bean

Let us assume we have a requirement. Set a longer session timeout for premium user account.
Users are authenticated upon session creation through SSO.

To easy meet the requirements just instantiate the CustomTimeoutSessionListener as Spring bean at resources.groovy. We also going to need some source of the user custom session timeout. Let say a ConfigService.
beans = {    
customTimeoutSessionListener(CustomTimeoutSessionListener) {
configService = ref('configService')
}
}

With such approach BootStrap.groovy has to by slightly modified. To keep control on listener instantation, instead of passing listener class type, Spring bean is injected by Grails and the instance passed:
class BootStrap {

def customTimeoutSessionListener

def init = { servletContext ->
servletContext.addListener(customTimeoutSessionListener)
}
}

An example CustomTimeoutSessionListener implementation can look like:
import javax.servlet.http.HttpSessionEvent    
import javax.servlet.http.HttpSessionListener
import your.app.ConfigService

class CustomTimeoutSessionListener implements HttpSessionListener {

ConfigService configService

@Override
void sessionCreated(HttpSessionEvent httpSessionEvent) {
httpSessionEvent.session.maxInactiveInterval = configService.sessionTimeoutSeconds
}

@Override
void sessionDestroyed(HttpSessionEvent httpSessionEvent) { /* nothing to implement */ }
}
Having at hand all power of the Spring IoC this is surely a good place to load some persisted user’s account stuff into the session or to notify any other adequate bean about user presence.

Wait, what about the user context?

Honest answer is: that depends on your case. Yet here’s an example of getSessionTimeoutMinutes() implementation using Spring Security:
import org.springframework.security.core.context.SecurityContextHolder    

class ConfigService {

static final int 3H = 3 * 60 * 60
static final int QUARTER = 15 * 60

int getSessionTimeoutSeconds() {

String username = SecurityContextHolder.context?.authentication?.principal
def account = Account.findByUsername(username)

return account?.premium ? 3H : QUARTER
}
}
This example is simplified. Does not contain much of defensive programming. Just an assumption that principal is already set and is a String - unique username. Thanks to Grails convention our ConfigService is transactional so the Account domain class can use GORM dynamic finder.
OK, config fetching implementation details are out of scope here anyway. You can get, load, fetch, obtain from wherever you like to. Domain persistence, principal object, role config, external file and so on...

Any gotchas?

There is one. When running grails test command, servletContext comes as some mocked class instance without addListener method. Thus we going to have a MissingMethodException when running tests :(

Solution is typical:
def init = { servletContext ->
if (Environment.current != Environment.TEST) {
servletContext.addListener(customTimeoutSessionListener)
}
}
An unnecessary obstacle if you ask me. Should I submit a Jira issue about that?

TL;DR

Just implement a HttpSessionListener. Create a Spring bean of the listener. Inject it into BootStrap.groovy and call servletContext.addListener(injectedListener).

Devoxx 2012 review


I'm sitting in a train to Charleroi, looking through a window at the Denmark landscape, street lights flashing by, people comming home from work, getting out for a Friday night party, or having a family dinner. To my left, guys from SoftwareMill are playing cards.
I don't really see them. My mind is busy elsewhere, sorting out and processing last two days in Antwerp, where 3400 developers, from 41 different countries, listened to 200 different sessions at the Devoxx, AFAIK the biggest Java conference this year.